简体   繁体   English

存在iframe时,与jquery.append等效的本机javascript

[英]native javascript equivalent to jquery.append when iframes are present

I am trying to use native javascript to append a string of html to a target div. 我正在尝试使用本机javascript将html字符串附加到目标div。 This works fine using: 使用以下方法可以正常工作:

var selector = document.getElementById('divid');
var str = '<div><h1>string of html content</h1></div>';
selector.innterHTML += str;

Except whenever the document contains an iframe it seems to hide the frame when appending the innerhtml. 除非文档包含iframe,否则在附加innerhtml时似乎会隐藏该框架。 I tried a work around as follows: 我尝试了以下方法:

var selector = document.getElementById('divid');
var str = '<div><h1>string of html content</h1></div>';
var div = document.createElement('div');
div.innerHTML = str;
selector.appendChild(div);

This works but now I am creating an unnecessary div container, is there a way to do this without creating a new element that won't erase the iframe? 这可行,但是现在我创建了一个不必要的div容器,有没有一种方法可以在不创建不会删除iframe的新元素的情况下做到这一点?

Except whenever the document contains an iframe it seems to hide the frame when appending the innerhtml 除非文档包含iframe,否则在附加innerhtml时似乎会隐藏该框架

See "innerHTML += ..." vs "appendChild(txtNode)" for the reason - modifying innerHTML creates a new iframe that reloads. 请参阅“ innerHTML + = ...”与“ appendChild(txtNode)”的原因-修改innerHTML会创建一个重新加载的新iframe。 Also have a look at What is better, appending new elements via DOM functions, or appending strings with HTML tags? 还可以看看通过DOM函数附加新元素或使用HTML标签附加字符串有什么更好的选择?

This works but now I am creating an unnecessary div container 这有效,但是现在我正在创建不必要的div容器

Just don't create an extra div , you have one in your HTML anyway: 只是不要创建额外的div ,无论如何您的HTML中都有一个:

var selector = document.getElementById('divid');
var div = selector.appendChild(document.createElement('div'));
div.innerHTML = '<h1>string of html content</h1>';

is there a way to do this without creating a new element that won't erase the iframe? 有没有一种方法可以在不创建不会删除iframe的新元素的情况下执行此操作?

You can also use the native insertAdjacentHTML method which is the equivalent to jQuery's append with a HTML string: 您还可以使用本地的insertAdjacentHTML方法 ,该方法等效于jQuery的带有HTML字符串的append

var selector = document.getElementById('divid');
selector.insertAdjacentHTML('beforeend', '<div><h1>string of html content</h1></div>');

This seems to work. 这似乎有效。

var parser = new DOMParser();
var el = parser.parseFromString(str, "text/html");
selector.appendChild(el.childNodes[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM