Javascript,再添加一个元素...
我正在学习这些东西,所以这是我最简单的脚本:
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
t.border=1;
// note the reverse order of adding child
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);
// more code to populate table rows and cells
document.getElementById("theBlah").appendChild(t);
alert(t);
}
现在我想添加一些将在 中显示的内容,所以我想:
td.appendChild(document.createTextNode(title));
这效果很好...... 但如果标题包含 html,例如一个简单的粗体标签,就像这样 Hello;名字!
我们该怎么做?
我认为我们为 创建一个新元素,但是......在那之后,我不知道该怎么做。 只是为了澄清,我希望最终结果是
Hello name!
最终出现在 TD 标签中,如下所示:
<td>Hello<b> name!</b></td>
请帮忙!!
编辑; 是的,我知道我可以通过 InnerHTML 做到这一点,但我需要这样做才能通过 Firefox AMO 政策 抱歉应该早点提到这一点......
I am learning this stuff so this is my most simple script:
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
t.border=1;
// note the reverse order of adding child
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);
// more code to populate table rows and cells
document.getElementById("theBlah").appendChild(t);
alert(t);
}
Now I want to add something that will be displayed in <td>
, so I figured:
td.appendChild(document.createTextNode(title));
which works great...
but if title contains html, for example a simple bold tag, like so Hello<b> name!</b>
how do we do that?
I think we create a new element for <b>
but... after that, i have no idea how to do it.
Just to clarify, I want the end result to be that Hello<b> name!</b>
ends up in the TD tag like this:
<td>Hello<b> name!</b></td>
Please help!!
EDIT;
Yes, I know I can do this via InnerHTML, but I need to do it this way to get it past Firefox AMO policies
Sorry shoulda mentioned this earlier...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
td.innerHTML
代替。这样您就可以放心地将标签作为标记传递。Try using
td.innerHTML
instead. That way you can pass your tags as markup without worry.您可以将innerHTML 分配给要附加的元素。
You'd assign the innerHTML to the element you want to append.
尝试:
结果:
Hello name!
示例:http://jsfiddle.net/hGF3e/
Try:
Result:
<td>Hello<b> name!</b></td>
Example: http://jsfiddle.net/hGF3e/
正如其他人提到的,您可以做的最简单的事情是:
您还可以这样做:
另外,正如您所知,
标记在技术上已被弃用。您应该使用
或
来代替。
As the other folks have mentioned, the simplest thing you can do is:
You can also do:
Also, just so you know, the
<b>
tag is technically deprecated. You should use<em>
or<strong>
instead.