我编写了一个功能,用于抓取网站上最受欢迎的文章。我执行了两次抓取,一次用于文章图片,另一次用于文章的链接和标题。然后我将每篇文章的图像、链接和标题合并到单独的对象中。从这里开始,我的目标是将此信息写入 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 创建与其他元素相同的表格的最佳方式
关于javascript - HTML DOM 和 Javascript : Uncaught TypeError: Cannot read property 'appendChild' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54857497/