Javascript, DOM: appendChild and textContent

Javascript, DOM: appendChild and textContent

本文关键字:and textContent appendChild DOM Javascript      更新时间:2023-09-26

我提交了一个Firefox插件到mozilla目录,它被拒绝了,因为这个:

item.innerHTML =   '<table style="border-collapse: collapse; width: 100%;">'
                  + '<tr><td style="line-height: inherit; padding: 0pt; width: 100%;">'
                   + word.title
                   + '</td></tr>'
                    + '</table>';

我和编辑谈过了,他告诉我"use a text node and then insert it using appendChild, textContent, etc"

对我来说,这听起来完全是胡言乱语,我从未使用过TextContent, appendChild等,我有点迷路了。你能告诉我如何做到上述,我会编辑其他13个实例,我有类似的东西在我的脚本?

谢谢!

您可能需要做以下操作:

var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    tr = document.createElement("tr"),
    td = document.createElement("td");
    t.style.width = "100%";
    // note the reverse order of adding child        
    tr.appendChild(td);
    tb.appendChild(tr);
    t.appendChild(tb);
   // more code to populate table rows and cells
   item.appendChild(t);

注意:由于浏览器之间的工作方式不同,因此以这种方式创建表有一些注意事项。我建议咨询MDN,以确定FF。

他希望你用JavaScript编程地创建HTML。读一读这篇文章,你就会明白了。如果您想了解更多信息,请发表评论。

比起使用innerHTML,他希望您使用一个以更直接的方式更改DOM的函数。列表末尾

将节点添加到指定父节点的子节点列表的末尾节点。如果节点已经存在,则从当前父节点中删除它节点,然后添加到新的父节点

https://developer.mozilla.org/En/DOM/Node.appendChild。格式为:var child = element.appendChild(child);

在你的例子中,我会这样做:

var newText = document.createTextNode(word.title);
locationInDom.appendChild(newText);

Where locationInDom是你要使用innerHTML的地方。如果innerHTML要放入一个表中,那么只需为特定的现有列添加一个id,并使用getElementById方法并在该点添加。