Console error in js: Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')

The console error message is:

Means: Uncaught TypeError: Cannot read property (read 'appendchild') of undefined

In other words, you don't have this attribute on the parent element when you use appendChild, so it can't be used.

At this point, you need to check whether you get the element wrong, or a logic problem.

At this point my js code is: (only the part that causes the error is shown)

	// 页面初始化
	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 < 3 ? "active" : "";

			// 创建节
			// console.log(val.list);
			val.list.forEach(function(cur) {
				// 创建li
				var li = document.createElement("li");

				// 给当前这个li赋值内容
				li.innerHTML = `<p>
									<i class="iconfont icon-bofang"></i>
									<span>${cur.name}</span>
								</p>
								<p>
									<span>${cur.time}开播</span>
									<span class="start">播放视频</span>
								</p>`;

				// 添加到ul中 
				ul.appendChild(li);
			});


			// 将ul添加到div中
			div.appendChild(ul);

			// 将div添加到kecheng中
			kecheng.appendChild(div);

		});

 As can be seen from the above figure, I wrote the acquisition element behind the calling method, and the content corresponding to the number of lines prompted when the error was reported is: kecheng. wrong.

According to the concept of pre-parsing: it is the code that loads var and function in advance before it is actually executed. (var only declares but not defines, function declares + defines)

It is known that in the preloading before the code is executed, the function bindData(classList) is called first, and then the course is defined, so the kecheng in the last line of the function bindData has not yet been defined. (The preloading idea is roughly as follows)

 Therefore, this type of error can be avoided by placing the function call after getting the element. as follows:

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

(A programming novice, please correct me if I make any mistakes, thank you~)

Guess you like

Origin blog.csdn.net/qq_56715703/article/details/128009637