Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

javascript - Javascript - 将HTML附加到没有innerHTML的容器元素(Javascript - Append HTML to container element without innerHTML)

I need a way to append HTML to a container element without using innerHTML.

(我需要一种方法将HTML附加到容器元素而不使用innerHTML。)

The reason why I do not want to use innerHTML is because when it is use like this:

(我不想使用innerHTML的原因是因为它使用时如下:)

element.innerHTML += htmldata

It works by replacing all of the html first before adding the old html plus the new html.

(它的工作原理是在添加旧的html和新的html之前先替换所有的html。)

This is not good because it resets dynamic media such as embedded flash videos...

(这不好,因为它重置了嵌入式Flash视频等动态媒体......)

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.

(然而,这种方式的问题是文档中现在有额外的span标记,我不想要。)

How can this be done then?

(那怎么办呢?)

Thanks!

(谢谢!)

  ask by Bob translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am surprised that none of the answers mentioned the insertAdjacentHTML() method.

(我很惊讶没有提到insertAdjacentHTML()方法的答案。)

Check it out here .

(在这里查看 。)

The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend").

(第一个参数是你想要附加字符串的地方(“beforebegin”,“afterbegin”,“beforeend”,“afterend”)。)

In the OP's situation you would use "beforeend".

(在OP的情况下,你会使用“beforeend”。)

The second parameter is just the html string.

(第二个参数只是html字符串。)

Basic usage:

(基本用法:)

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...