文章詳情頁
js控制臺報錯Uncaught TypeError: Cannot read properties of undefined (r
瀏覽:5日期:2022-06-12 15:51:51
控制臺錯誤提示為:
意思是:未捕獲的類型錯誤: 無法讀取未定義的屬性(讀取‘ appendchild’)
也就是說,你在使用appendChild時的父元素上沒有這個屬性,所以沒法使用。
此時,需要檢查你獲取元素是否有誤,或者是邏輯問題。
此時我的js代碼為:(只展示引起錯誤的部分)
// 頁面初始化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>`;// 創建ulvar ul = document.createElement('ul');// 設置類名ul.className = index < 3 ? 'active' : '';// 創建節// console.log(val.list);val.list.forEach(function(cur) {// 創建livar 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);});從上圖可以看出,我把獲取元素寫到了調用方法的后面,且報錯時提示的行數對應的內容是:kecheng.appendChild(div);也就是說是kecheng在獲取或者別的方面出了錯。
根據預解析的概念:就是代碼在真正執行之前將var和funtion進行提前的加載。(var只聲明不定義,function聲明+定義 )
得知:在代碼執行前的預加載中是先把函數bindData(classList)調用,之后才定義了課程,所以在函數bindData中最后一行的kecheng還未定義。(預加載思路圖大致如下)
所以,只要把函數調用放在獲取元素之后就可以避免這類型錯誤。如下:
// 獲取元素var kecheng = document.querySelector('.classlist .kecheng');// 頁面初始化bindData(classList);到此這篇關于js控制臺報錯Uncaught TypeError: Cannot read properties of undefined (reading ‘appendChild‘)的解決的文章就介紹到這了,更多相關js控制臺報錯Uncaught TypeError內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
標簽:
JavaScript
排行榜