我正在做一些事情,需要我在文档加载时向文档添加鼠标/键盘事件侦听器。
document/window.addEventListener()运行良好,直到我遇到了框架集/框架/iframes。
我做了一些变通方法,比如遍历框架集的所有框架,并向它们添加事件侦听器。
然后我意识到帧是在DOM之后动态加载的。所以我做了这样的事情:
bindListenersToFrame: function(element){
var $ = domUtils.jQuery;
$(element).ready(function(){
if(element.tagName == "FRAMESET" || element.tagName == "BODY"){
for(var i=0; i < element.children.length; i++){
domUtils.bindListenersToFrame(element.children[i]);
}
}
if(element.tagName == "FRAME" || element.tagName == "IFRAME"){
$('iframe').load(function(){
domUtils.addListener(element);
if(element.contentDocument.documentElement){
for(var i=0; i < element.contentDocument.documentElement.children.length; i++){
domUtils.bindListenersToFrame(element.contentDocument.documentElement.children[i]);
}
}
});
}
});
}上面的方法本质上是递归的,domUtils只是一个带有"addListener“方法的对象。
任何帮助都将不胜感激。谢谢。
发布于 2018-11-02 20:40:27
试试这个:
$('body').on('click','iframe',function(e) {
console.log("clicked");
});发布于 2018-11-14 18:31:44
我建议递归地检查帧并附加侦听器。这真的不应该这样做,但这是唯一的方法。请注意,由于对代码段的沙箱限制,此代码段不能在SO上工作。我已经测试过了,它可以在本地服务器上工作。我也找不到(在有限的时间内)绕过我目前正在使用的setTimeout的方法。感觉它是在页面加载之前应用的,但我看不到这些load事件的任何影响,所以为了演示它是如何工作的,请检查以下内容:
function nestedIFrameEventAttacher( iframe, event, handler ){
const content = iframe.contentDocument || (iframe.contentWindow ? iframe.contentWindow .document : iframe);
const body = content.querySelector( 'body' );
body.addEventListener( event, handler );
// I have tried attaching `load` and `DOMContentLoaded` events
// to the `iframe` and the `body` but none of them seemed to trigger.
// This is therefor not guaranteed to work, but you can start from this.
setTimeout(function(){
Array.from( body.querySelectorAll( 'iframe' ) ).forEach(iframe => {
nestedIFrameEventAttacher( iframe, event, handler );
});
}, 100);
}
const output = document.getElementById( 'output' )
nestedIFrameEventAttacher( document, 'click', function( event ){
output.textContent = this.querySelector( 'h1' ).textContent;
});#output{ color: red; }<div id="output">Stealie the Dog</div>
<h1>Root</h1>
<iframe srcdoc="<html><head></head><body><h1>Second</h1><iframe srcdoc='<html><head></head><body><h1>Deeper</h2></body></html>'></iframe></body></html>" width="100%" height="500px"></iframe>
发布于 2018-11-02 20:35:12
为什么不将监听器添加到<body>
$('body').click(function(e) {
console.log("clicked")
})https://stackoverflow.com/questions/53117403
复制相似问题