繁体   English   中英

HTML DOM和Javascript:未捕获的TypeError:无法读取未定义的属性'appendChild'

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM