在动态创建的iframe中侦听并单击文本



我想在单击iframe中的文本时添加事件。此iframe是在加载文档后创建的。创建后,在iframe元素中创建了文档对象#document。在此代码中,无法捕获iframe中的点击文本。

<html>
<head>
<script src="../ext/plugins/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
//add iframe
var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
$('#iframe-holder').append(iframe);
})
$(document).on('click','#iframe-holder > iframe',function(){
console.log('you have clicked text in iframe');
//do something
});
</script>
</head>
<body>
<div id="iframe-holder">

</div>
</body>

您在iframe本身上添加了一个点击监听器:

$(document).on('click','#iframe-holder > iframe',function(){
console.log('you have clicked text in iframe');
//do something
});

相反,你应该在iframe中的文本上添加一个点击事件,所以你应该这样做:

const iframe = document.querySelector('#iframe-holder > iframe');
iframe.onload = function() {
const iframeDocument = iframe.contentWindow.document;
iframeDocument.addEventListener('click', function(e) {
if (e.target.tagName.toLowerCase() == 'span') { // Element clicked inside iframe is a span element
// Do your work here
}
}) 
}

我测试了@Teemu和@Tanay的答案。当我在document.addEventListener('load',function(event){//sucessfully fired when added here})中添加时,它就起作用了。然后,我将iframe.src更改为源文档page1.html

<html>
<head>
<script src="../ext/plugins/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
//add iframe
var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
//iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
iframe.src = 'page1.html';
$('#iframe-holder').append(iframe);
})
document.addEventListener(
'load',
function(event){
//1:
$($('#iframe-holder > iframe')[0].contentDocument).on('click', function (e) {
console.log('ln34');
});
//2:    
const iframe = document.querySelector('#iframe-holder > iframe');
iframe.onload = function() {
const iframeDocument = iframe.contentWindow.document;
iframeDocument.addEventListener('click', function(e) {
console.log('ln43');
})
}
},
true // Capture event
);
</script>
</head>
<body>
<div id="iframe-holder">

</div>
</body>

谢谢你的帮助。

相关内容

最新更新