IT俱乐部 JavaScript js控制台报错Uncaught TypeError: Cannot read properties of undefined (reading ‘appendChild‘)的解决

js控制台报错Uncaught TypeError: Cannot read properties of undefined (reading ‘appendChild‘)的解决

控制台错误提示为:

意思是:未捕获的类型错误: 无法读取未定义的属性(读取‘ appendchild’)

也就是说,你在使用appendChild时的父元素上没有这个属性,所以没法使用。

此时,需要检查你获取元素是否有误,或者是逻辑问题。

此时我的js代码为:(只展示引起错误的部分)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 页面初始化
    bindData(classList);
    // 获取元素
    var kecheng = document.querySelector(".classlist .kecheng");
    // 数据绑定
    // data:数据(数组)
    function bindData(data) {
        // 循环遍历数组
        data.forEach(function(val, index) {
            // console.log(val,index);
            // 创建章
            var div = document.createElement("div");
            // 设置类名
            div.className = "detail";
            // 赋值内容
            div.innerHTML =
                `<p class="title">${val.title}(含${val.num}期)<i class="iconfont iconupanddown ${index < 3 ?'icon-top1':'icon-down'}"></i></p>`;
            // 创建ul
            var ul = document.createElement("ul");
            // 设置类名
            ul.className = index
                                    <i class="iconfont icon-bofang"></i>
                                    <span>${cur.name}</span>
                                 
                                <p>
                                    <span>${cur.time}开播</span>
                                    <span class="start">播放视频</span>
                                </p>`;
                // 添加到ul中
                ul.appendChild(li);
            });
            // 将ul添加到div中
            div.appendChild(ul);
            // 将div添加到kecheng中
            kecheng.appendChild(div);
        });

 从上图可以看出,我把获取元素写到了调用方法的后面,且报错时提示的行数对应的内容是:kecheng.appendChild(div);也就是说是kecheng在获取或者别的方面出了错。

根据预解析的概念:就是代码在真正执行之前将var和funtion进行提前的加载。(var只声明不定义,function声明+定义 )

得知:在代码执行前的预加载中是先把函数bindData(classList)调用,之后才定义了课程,所以在函数bindData中最后一行的kecheng还未定义。(预加载思路图大致如下)

 所以,只要把函数调用放在获取元素之后就可以避免这类型错误。如下:

1
2
3
4
// 获取元素
var kecheng = document.querySelector(".classlist .kecheng");
// 页面初始化
bindData(classList);

到此这篇关于js控制台报错Uncaught TypeError: Cannot read properties of undefined (reading ‘appendChild‘)的解决的文章就介绍到这了,更多相关js控制台报错Uncaught TypeError内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/js/8505.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部