js控制臺(tái)報(bào)錯(cuò)Uncaught TypeError: Cannot read properties of undefined (r
控制臺(tái)錯(cuò)誤提示為:
意思是:未捕獲的類型錯(cuò)誤: 無法讀取未定義的屬性(讀取‘ appendchild’)
也就是說,你在使用appendChild時(shí)的父元素上沒有這個(gè)屬性,所以沒法使用。
此時(shí),需要檢查你獲取元素是否有誤,或者是邏輯問題。
此時(shí)我的js代碼為:(只展示引起錯(cuò)誤的部分)
// 頁面初始化bindData(classList);// 獲取元素var kecheng = document.querySelector('.classlist .kecheng'); // 數(shù)據(jù)綁定// data:數(shù)據(jù)(數(shù)組)function bindData(data) {// 循環(huán)遍歷數(shù)組data.forEach(function(val, index) {// console.log(val,index);// 創(chuàng)建章var div = document.createElement('div');// 設(shè)置類名div.className = 'detail';// 賦值內(nèi)容div.innerHTML =`<p class='title'>${val.title}(含${val.num}期)<i class='iconfont iconupanddown ${index < 3 ?'icon-top1':'icon-down'}'></i></p>`;// 創(chuàng)建ulvar ul = document.createElement('ul');// 設(shè)置類名ul.className = index < 3 ? 'active' : '';// 創(chuàng)建節(jié)// console.log(val.list);val.list.forEach(function(cur) {// 創(chuàng)建livar li = document.createElement('li');// 給當(dāng)前這個(gè)li賦值內(nèi)容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);});從上圖可以看出,我把獲取元素寫到了調(diào)用方法的后面,且報(bào)錯(cuò)時(shí)提示的行數(shù)對(duì)應(yīng)的內(nèi)容是:kecheng.appendChild(div);也就是說是kecheng在獲取或者別的方面出了錯(cuò)。
根據(jù)預(yù)解析的概念:就是代碼在真正執(zhí)行之前將var和funtion進(jìn)行提前的加載。(var只聲明不定義,function聲明+定義 )
得知:在代碼執(zhí)行前的預(yù)加載中是先把函數(shù)bindData(classList)調(diào)用,之后才定義了課程,所以在函數(shù)bindData中最后一行的kecheng還未定義。(預(yù)加載思路圖大致如下)
所以,只要把函數(shù)調(diào)用放在獲取元素之后就可以避免這類型錯(cuò)誤。如下:
// 獲取元素var kecheng = document.querySelector('.classlist .kecheng');// 頁面初始化bindData(classList);到此這篇關(guān)于js控制臺(tái)報(bào)錯(cuò)Uncaught TypeError: Cannot read properties of undefined (reading ‘appendChild‘)的解決的文章就介紹到這了,更多相關(guān)js控制臺(tái)報(bào)錯(cuò)Uncaught TypeError內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
