为什么是“element.innerHTML + =”错误的代码? [英] Why is "element.innerHTML+=" bad code?
问题描述
我被告知不要使用 element.innerHTML + = ...
来追加内容:
var str =< div> hello world< / div>;
var elm = document.getElementById(targetID);
elm.innerHTML + = str; //不是个好主意?
它有什么问题?我还有其他的选择吗?$ b $每当设置 innerHTML
时,HTML必须被解析,一个DOM被构造并被插入放入文件中。例如,如果 elm.innerHTML
包含数千个div,表格,列表,图片等,则需要时间。等等,然后调用 .innerHTML + = ...
会导致解析器重新解析所有这些东西。这也可能会中断已经构建的DOM元素的引用并导致其他混乱。实际上,你想要做的就是在最后添加一个新元素。
最好只调用 appendChild
:
var newElement = document.createElement('div');
newElement.innerHTML ='< div> Hello World!< / div>';
elm.appendChild(newElement);
通过这种方式, + =
运算符,而不是重新解析现有内容。我还没有研究过这个。
I have been told not to append stuff using element.innerHTML += ...
like this:
var str = "<div>hello world</div>";
var elm = document.getElementById("targetID");
elm.innerHTML += str; //not a good idea?
What is wrong with it?, what other alternatives do I have?
Every time innerHTML
is set, the HTML has to be parsed, a DOM constructed, and inserted into the document. This takes time.
For example, if elm.innerHTML
has thousands of divs, tables, lists, images, etc, then calling .innerHTML += ...
is going to cause the parser to re-parse all that stuff over again. This could also break references to already constructed DOM elements and cause other chaos. In reality, all you want to do is append a single new element to the end.
It's better to just call appendChild
:
var newElement = document.createElement('div');
newElement.innerHTML = '<div>Hello World!</div>';
elm.appendChild(newElement);
This way, the existing contents of elm
are not parsed again.
NOTE: It's possible that [some] browsers are smart enough to optimize the +=
operator and not re-parse the existing contents. I have not researched this.
这篇关于为什么是“element.innerHTML + =”错误的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!