本文介绍了将事件添加到动态添加到iframe内的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的HTML代码
i have an HTML code like this
<iframe id="myframe">
<ul>
<li>
<a href="" class="add-section">add section</a>
<div>...</div>
</li>
<ul>
</iframe>
点击添加部分链接后,< li> ;
包含此(添加部分)链接后复制并插入,代码变为这样。
when the "add-section" link is clicked the parrent <li>
that contains this (add-section) link get duplicated and inserted after, and the code become like this.
<iframe id="myframe">
<ul>
<li>
<a href="" class="add-section">add section</a>
<div>...</div>
</li>
<li>
<a href="" class="add-section">add section</a>
<div>...</div>
</li>
<ul>
</iframe>
我使用这个jquery代码来实现这一点,它运行得很好。
i use this jquery code to achieve this and it works just fine.
$($("#myframe").contents().find('.add-section')).on("click",function(e){
e.preventDefault();
$(this).parent().after("<li>"+$(this).parent().html()+"</li>");
});
我的问题是当我点击新创建的(添加部分)链接时代码不会执行。
My problem is when i click in the new created (add-section) link the code won't execute.
我的问题是如何将点击事件添加到iframe中最新添加的元素。
My question is how to add a click event to the newest added element inside the iframe.
在此先感谢。
推荐答案
尝试将事件绑定到body元素,然后使用事件委派,如
Try to bind the event to the body element and then use event delegation like
$("#myframe").contents().find('body').on("click", '.add-section', function (e) {
e.preventDefault();
$(this).parent().after("<li>" + $(this).parent().html() + "</li>");
});
这篇关于将事件添加到动态添加到iframe内的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!