Javascript - 将HTML追加到没有innerHTML的容器元素 [英] Javascript - Append HTML to container element without innerHTML

查看:314
本文介绍了Javascript - 将HTML追加到没有innerHTML的容器元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种将HTML附加到容器元素而不使用innerHTML的方法。我不想使用innerHTML的原因是,当它使用像这样:

element.innerHTML + = htmldata $ b

它通过在添加旧的html和新的html之前先替换所有的html。这是不好的,因为它重置动态媒体,如嵌入式Flash视频......



我可以这样做:

  var e = document.createElement('span'); 
e.innerHTML = htmldata;
element.appendChild(e);

然而,这种方式的问题是现在文档中存在额外的span标签不想要。



那么这怎么做呢?谢谢!

解决方案

给出一个替代方案(如使用 DocumentFragment 似乎工作):您可以通过迭代新生成的节点的子节点来模拟它,并只添加这些节点。

  var e = document.createElement('div'); 
e.innerHTML = htmldata;

while(e.firstChild){
element.appendChild(e.firstChild);
}


I need a way to append HTML to a container element without using innerHTML. The reason why I do not want to use innerHTML is because when it is use like this:

element.innerHTML += htmldata

It works by replacing all of the html first before adding the old html plus the new html. This is not good because it resets dynamic media such as embedded flash videos...

I could do it this way which works:

var e = document.createElement('span');
e.innerHTML = htmldata;
element.appendChild(e);

However the problem with that way is that there is that extra span tag in the document now which I do not want.

How can this be done then? Thanks!

解决方案

To give an alternative (as using DocumentFragment does not seem to work): You can simulate it by iterating over the children of the newly generated node and only append those.

var e = document.createElement('div');
e.innerHTML = htmldata;

while(e.firstChild) {
    element.appendChild(e.firstChild);
}

这篇关于Javascript - 将HTML追加到没有innerHTML的容器元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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