Firefox 和 Chrome 中的 lastchild.appendchild
以下代码
var descriptdiv = document.createElement("div");
document.body.lastChild.appendChild(descriptdiv);
在 IE 中有效,但在 FireFox 和 Chrome 中无效。我怎样才能让它在这些浏览器中也工作?
The following code
var descriptdiv = document.createElement("div");
document.body.lastChild.appendChild(descriptdiv);
works in IE, but doesn't work in FireFox and Chrome. How can I get it to work in those browsers too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您最有可能看到的是 Firefox/Chrome 将文本节点返回为
lastChild
。这是因为这些浏览器会将代码末尾的任何空格/换行符作为文本节点返回。由于您无法将 div 附加到文本节点,因此代码失败。另一方面,IE 将忽略空格/换行符并返回最后一个元素,您可以成功附加到该元素。您可以使用以下之类的函数来获取最后一个元素:
What you're most likely seeing is Firefox/Chrome returning text nodes as
lastChild
. This is because these browsers will return any whitespace/newlines at the end of your code as text nodes. Since you can't append a div to a text node, the code fails.IE on the other hand will ignore the whitespace/newlines and return the last element, which you can successfully append to. You can use a function like the following to get the last element:
您不能将块元素添加到 img、br、hr 等许多其他元素中,
有些你可以做,但你永远不需要。
您可能对您想要的容器有所了解。
/^(DIV|P|TD|LI|DT|DD|BLOCKQUOTE|FORM|文章|ASIDE|页脚|标题|导航|部分)/i
You cannot add a block element to an img, br, hr and many others,
and there are some you can that you won't ever need to.
You probably have some idea of the container you want.
/^(DIV|P|TD|LI|DT|DD|BLOCKQUOTE|FORM|ARTICLE|ASIDE|FOOTER|HEADER|NAV|SECTION)/i