简体   繁体   English

如果插入iframe,则在插入元素时重置页面

[英]Page resets when inserting element if there's an iframe in

I have the following HTML: 我有以下HTML:

<div id="main"><div><iframe></iframe></div>
<div>Content</div>
<div>Content</div>
<div id="clickme">Click</div>
</div>

#clickme has a click event that inserts a div after it. #clickme具有click事件,该事件在其后插入div。 So basically after clicking on #clickme , the structure should be like this: 因此,基本上,在单击#clickme ,结构应如下所示:

<div><div><iframe></iframe></div>
<div>Content</div>
<div>Content</div>
<div id="clickme">Click</div>
<div>Inserted div</div>
</div>

After the div is inserted, the page seems to load something. 插入div后,页面似乎加载了一些东西。 In the console, it looks like the iframe is reloading(it show a GET request to the page that is loaded in the iframe). 在控制台中,看起来iframe正在重新加载(它显示对iframe中加载的页面的GET请求)。 This would not be so big of a problem, but all the events are removed from elements, which is a problem. 这不是什么大问题,但是所有事件都已从元素中删除,这是一个问题。 I tried removing the iframe and the problem disappeared. 我尝试删除iframe,问题消失了。 Do you have any idea about what causes this? 您是否知道这是什么原因?

The JS: JS:

document.querySelector("#clickme").addEventListener("click", function(){
document.querySelector("#main").innerHTML+="<div></div>";
})

The += operator with innerHTML causes a conversion of all the nodes inside of main into plain text before concatenating the argument. 使用innerHTML的+ =运算符会在连接参数之前将main内部的所有节点转换为纯文本。 Afterwards it clears the actual node and applies the newly rendered string. 之后,它将清除实际节点并应用新呈现的字符串。

We need to insert the new HTML without touching the existing: 我们需要插入新的HTML而不接触现有的HTML:

document.querySelector("#clickme").addEventListener("click", function(event){
  event.target.insertAdjacentHTML('afterend', '<div>Inserted div</div>');
}

Es a side effect this code will consume less time. 副作用是此代码将占用更少的时间。

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

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