jQuery OnClick 函数不会在 iframe 上触发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16792953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:47:59  来源:igfitidea点击:

OnClick function doesnt fire on iframe?

javascriptjquery

提问by user198989

I am trying to make click function fire when iframe is being clicked but It doesn't fire. Is it possible to do it ?

我试图在点击 iframe 时触发点击功能,但它没有触发。有可能做到吗?

$("#iframe").click(function() {
alert("works");
});

<iframe id="iframe" src="http://site.com" scrolling="no"></iframe>

回答by Willem

Another solution is to overlay a transparent div and add a click event to that div. Working sample: http://jsfiddle.net/w1ll3m/AxJHH/

另一种解决方案是覆盖一个透明的 div 并向该 div 添加一个点击事件。工作示例:http: //jsfiddle.net/w1ll3m/AxJHH/

<div class="container">
    <iframe src="#url"></iframe>
    <div class="overlay"></div>
</div>

css to position the div.overlay over the iframe:

css 将 div.overlay 定位在 iframe 上:

.container{position:relative;float:left;}
.overlay{top:0;left:0;width:100%;height:100%;position:absolute;}

Add the event:

添加事件:

$('.overlay').click(function(){alert('hello');});

回答by r043v

$iframe = $( document.getElementById("myiframe").contentWindow.document );

$iframe.find("body").click(function(){
    alert("hey");
});

http://jsfiddle.net/cRDjV/81/

http://jsfiddle.net/cRDjV/81/

回答by Farkie

No. You need to do this inside the iFrame, rather than the parent.

不。您需要在 iFrame 中执行此操作,而不是在父级中执行此操作。

You could however, add an EventListener: Adding click event handler to iframe

但是,您可以添加一个 EventListener:将单击事件处理程序添加到 iframe