[英]How to add click event to the dynamic element of an iframe?
I'm adding some html element to the iframe by using innerHTML like below 我通过使用innerHTML将一些html元素添加到iframe中,如下所示
var iframe = document.getElementById('composer_frame'), iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = "<a id='myAnch'>Click</a>";
and i want to write a function which should be exicute by clicking anchor "#myAnch" 并且我想编写一个应通过单击锚点“ #myAnch”将其删除的函数
Try this: 尝试这个:
$("#composer_frame").contents().find("#myAnch").on('click',function(){
//do stuff
});
you can write function for element like this 您可以为这样的元素编写函数
$('#myAnch', iframedoc).click(function() {console.log("a");})
but you should put this code on parent html page. 但是您应该将此代码放在父html页面上。
Explanation:- Since you are trying to add a event on dynamically created element inside an iframe, so you have to bind it through parent reference. 说明:-由于您试图在iframe中动态创建的元素上添加事件,因此您必须通过父引用将其绑定。
That means based on parent element try to find-out the dynamically added element and then add event on it.(as jQuery din't recognise dynamically added element directly) 这意味着基于父元素尝试找出动态添加的元素,然后在其上添加事件。(因为jQuery无法直接识别动态添加的元素)
So do it like below:- 因此,如下所示:-
$("#composer_frame").contents().find('#myAnch').on("click", function (e) {
e.preventDefault();
alert('clicked');
});
Working snippet:- https://jsfiddle.net/sycf9nz6/ 工作片段:-https: //jsfiddle.net/sycf9nz6/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.