Html InnerHTML 追加而不是替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18539992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:51:03  来源:igfitidea点击:

InnerHTML append instead of replacing

javascripthtml

提问by BackSlash

I'm using this code to update a divwith an AJAX request

我正在使用此代码div通过 AJAX 请求更新 a

var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("some_id").innerHTML += xmlhttp.responseText;
    }
}
xmlhttp.open("GET", "http://example.com/");
xmlhttp.setRequestHeader('Content-Type', 'utf8');
xmlhttp.send();

Everything works fine, the problem is that when the divwith id some_idhas a lot of content in it i can see the content disappearing and then appearing updated after the AJAX request has been executed.

一切正常,问题是当divwith id 中some_id有很多内容时,我可以看到内容消失,然后在执行 AJAX 请求后出现更新。

I think that it's because

我认为这是因为

document.getElementById("some_id").innerHTML += xmlhttp.responseText;

Is deleting and replacing the innerHTMLof the divwith the previous innerHTMLplus the new content, resulting in a previous content → blank → updated contentbehaviour.

被删除和更换innerHTMLdiv与前innerHTML加上新的内容,从而导致previous content → blank → updated content行为。

Is there a way to appendthe new content to the divinstead of replacing its whole content with the new one?

有没有办法新内容附加div而不是用新内容替换其整个内容?

回答by David says reinstate Monica

Assuming that htmlhttp.responseTextis a node:

假设这htmlhttp.responseText是一个节点:

document.getElementById("some_id").appendChild(xmlhttp.responseText);

If you have only a string of HTML (which seems likely), then:

如果您只有一串 HTML(这似乎很可能),则:

var newElement = document.createElement('div');
newElement.innerHTML = xmlhttp.responseText;
document.getElementById("some_id").appendChild(newElement);

On the other hand, if you must append new elements from a string:

另一方面,如果您必须从字符串中附加新元素:

// getting a reference to the relevant element we're adding to:
var container = document.getElementById("some_id"),
    // creating a new element to contain the 'xmlhttp.responseText'
    newElement = document.createElement('div');
// setting the innerHTML of the 'newElement' to whatever 'xmlhttp.responseText' is:
newElement.innerHTML = xmlhttp.responseText;

/* (repeatedly) removing the firstChild, and appending it to the 'container',
   of the 'newElement' until it's empty: */
while (newElement.firstChild) {
    container.appendChild(newElement.firstChild);
}
// removing the now empty 'newElement':
newElement.parentNode.removeChild(newElement);

References:

参考:

回答by oldergod

You could use Element.insertAdjacentHTML().

你可以使用Element.insertAdjacentHTML().

insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation.

insertAdjacentHTML() 将指定文本解析为 HTML 或 XML,并将结果节点插入到 DOM 树的指定位置。它不会重新解析正在使用它的元素,因此它不会破坏元素内的现有元素。这一点,避免了额外的序列化步骤,使其比直接的 innerHTML 操作快得多。

I guess you would do

我猜你会这样做

const div = document.getElementById("some_id");
div.insertAdjacentHTML('beforeend', xmlhttp.responseText);;

回答by Ankit Agrawal

old_html = document.getElementById("some_id").innerHTML;
document.getElementById("some_id").innerHTML = old_html+xmlhttp.responseText;