innerHTML的内部运作 [英] Inner workings of innerHTML

查看:128
本文介绍了innerHTML的内部运作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图迭代地更改Id的innerHTML,例如:

I was trying to iteratively change the innerHTML of an Id, like:

document.getElementById("test").innerHTML += "<br />"

document.getElementById("test").innerHTML += "<table>" + blahblah + "</table>"

但我发现它并不一定按顺序放置我的标签。

but I found that it didn't necessarily put my tags in sequence.

当然,这个方法很糟糕,我只是改变了所有内容以继续添加一个字符串,我最后将其分配给Id的innerHTML。

Of course, this method sucks, and I just changed everything to keep adding to a string, which I assign at the end to the innerHTML of the Id.

我的问题是:

innerHTML究竟对我插入的标签做了什么,是确定性的,是否特定于浏览器?

推荐答案

根据我的经验,大多数时候浏览器会尝试更正HTML 1 在将其注入DOM之前。如果您想以这种方式构建< ul>

In my experience most of the time a browser tries to correct the HTML1 before injecting it into the DOM. If you wanted to build a <ul> this way:

someElement.innerHTML += '<ul>';
someElement.innerHTML += '<li>some li</li>';
someElement.innerHTML += '<li>some other li</li>';
someElement.innerHTML += '</ul>';

例如,Chrome会产生以下结果:

In for example Chrome that would have resulted in:

<ul></ul>
 <li>some li</li>
 <li>some other li</li>
<ul></ul>

因此,innerHTML可以提供不可预测的结果,因为每次使用它时,HTML都会被更正浏览器(和浏览器的不同之处也在于它们)。对于表/表元素尤其如此(尤其是在IE中(因此MS发明了 innerHTML ))。如果你希望你的html完全按照的意图,坚持使用DOM方法( createElement / appendChild 等),或者首先使用innerHTML构建一个你要插入的完整元素的字符串,然后插入它,换句话说,不要使用 innerHTML 包含不完整HTML的字符串。

So, innerHTML can give unpredictable results, because every time you use it, the HTML is corrected by the browser (and browsers differ in the way they do it too). This is especially true for table/table elements (and even more especially so in IE (MS invented innerHTML by the way;)). If you want your html to be absolutely the way you intended it, stick to DOM methods (createElement/appendChild etc.), or first build up a string of the complete element you want to insert using innerHTML, then insert it, in other words, don't use innerHTML with strings containing incomplete HTML.

为了完整,我引用 PPK的quirksmode


如果你在IE中通过
innerHTML删除元素,其内容是
擦除,只有元素本身
(即开始和结束标签)
仍然存在。如果你想删除你可能想在以后的
重新插入的节点
,请使用DOM方法,例如
removeChild()

If you remove elements through innerHTML in IE, their content is wiped and only the element itself (i.e. opening and closing tags) remain. If you want to remove nodes that you may want to reinsert at a later time, use DOM methods such as removeChild()

1 更多技术:我认为每个浏览器都应用自己的 HTML片段解析算法

这篇关于innerHTML的内部运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆