You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch与WordPress自定义REST API追加文本时遇ReferenceError错误求助

问题分析与修复方案

错误原因

getElementsByClassName is not defined 这个错误主要有两种可能:

  1. 代码执行时机过早,DOM还没完全加载完成,导致document对象的相关方法无法正常访问(比如代码直接放在<head>标签里,没有等待DOM就绪)
  2. 代码中意外覆盖了document变量(比如之前错误声明过var document = ...这类代码)

另外你的代码还有一个潜在问题:使用var i会导致Promise回调执行时,i已经变成循环结束后的最大值,最终会出现重复操作元素或者索引越界的情况。

修复后的代码

// 等待DOM完全加载后再执行代码
document.addEventListener('DOMContentLoaded', function() {
    // 提前缓存元素,避免重复查询DOM,提升性能
    const titleElements = document.getElementsByClassName("elementor-post__title");
    const excerptElements = document.getElementsByClassName("elementor-post__excerpt");

    // 把HTMLCollection转为数组,用forEach遍历解决var的作用域问题
    Array.from(titleElements).forEach(function(titleEl, index) {
        const postTitle = titleEl.innerText.trim();
        // 对请求参数编码,避免特殊字符导致请求异常
        fetch(`https://localhost/paperclasslk/wp-json/quiz/v1/search?name=${encodeURIComponent(postTitle)}`)
            .then(res => res.json())
            .then(d => {
                const para = document.createElement("p");
                if (d.quiz_max_score === null) {
                    para.innerText = `Quiz ${index + 1} score is: No score`;
                } else {
                    para.innerText = `Quiz ${index + 1} score is: ${d.quiz_max_score}`;
                }
                // 确保对应位置的摘要元素存在,再执行追加操作
                if (excerptElements[index]) {
                    excerptElements[index].appendChild(para);
                }
            })
            .catch(err => {
                // 捕获请求错误,方便调试排查
                console.error('请求出错:', err);
            });
    });
});

关键修复点

  • 用DOMContentLoaded事件保证DOM加载完成后再执行代码,避免DOM相关方法无法访问
  • 缓存元素集合,减少重复DOM查询的开销
  • 用Array.from()+forEach替代var循环,解决异步回调中索引混乱的问题
  • 用encodeURIComponent()处理请求参数,避免标题含特殊字符导致请求失败
  • 添加错误捕获逻辑,方便排查API调用问题
  • 增加元素存在性判断,避免出现Cannot read property 'appendChild' of undefined错误

内容的提问来源于stack exchange,提问作者kimshee16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:45:58