![](/img/trans.png)
[英]Uncaught TypeError: Cannot read property 'appendChild' of undefined after Ajax call
[英]HTML DOM and Javascript: Uncaught TypeError: Cannot read property 'appendChild' of undefined
我編寫了一個功能,可以抓取網站上最受歡迎的文章。 我執行兩次刮擦,一個用於文章圖像,另一個用於文章的鏈接和標題。 然后,將每篇文章的圖像,鏈接和標題合並到單獨的對象中。 從這里開始,我的目標是將此信息寫入html文檔。 我為每篇文章創建一個表格行。 每行具有三個td:一個用於標題,圖像和鏈接。 我收到的錯誤如下所示。 我在出現錯誤的地方放了**。 當我嘗試將表格行追加到表格時,就會發生這種情況。 注意:這是一個小項目。 我不會為了任何個人利益而抓取網站。
VM51039:35 Uncaught TypeError: Cannot read property 'appendChild' of undefined
at <anonymous>:35:46
at Array.forEach (<anonymous>)
at m_getArticles (<anonymous>:12:15)
at <anonymous>:1:1
var m_getArticles = function(){
var article_nameANDlink = d3.selectAll('.grid.most-popular__grid h3>a').nodes();
var article_img = d3.selectAll('.grid.most-popular__grid picture>img').nodes();
var combination = [];
for (i=0; i<article_nameANDlink.length; i++) {
var info = new Object();
info.nameANDlink=article_nameANDlink[i];
info.img=article_img[i];
combination.push(info);
}
combination.forEach(function(d, index, arr) {
var link = d.nameANDlink.getAttribute("href");
console.log(link);
var name = d.nameANDlink.innerText;
console.log(name);
var img = d.img.getAttribute("src");
console.log(img);
var header = document.createElement("p");
var title = document.createTextNode(name);
header.appendChild(title);
var present = document.createElement("img");
present.setAttribute("img",img);
var provide = document.createElement("a");
provide.setAttribute("a",link);
provide.innerText="Read Article";
var nth_article = document.createElement("TR");
nth_article.setAttribute("id","row"+index);
document.getElementsByTagName("table")[0].**appendChild(nth_article)**;
var within_info = document.createElement("td");
within_info.setAttribute("id","within_info"+index);
document.getElementById("row"+index).appendChild(header);
var within_img = document.createElement("td");
within_img.setAttribute("id","within_img"+index);
document.getElementById("row"+index).appendChild(present);
var within_img = document.createElement("td");
within_img.setAttribute("id","within_link"+index);
document.getElementById("row"+index).appendChild(provide);
})
}
如果您的表元素已經存在,請嘗試使用var
var mytable = document.getElementsByTagName("table")[0];
mytable.appendChild(nth_article);
使用js創建表的最佳方式與其他元素相同
將獲得的表元素存儲在變量中,並檢查其是否未定義(如果未定義),然后創建表元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.