Javascript 将点击事件处理程序添加到 iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6452502/
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-23 21:47:35  来源:igfitidea点击:

Adding click event handler to iframe

javascriptiframeonclickaddeventlistener

提问by samach

I want to handle clickevent on an iframewith a handler that gets the iframe's id as parameter.

我想click使用一个iframeiframeid 作为参数的处理程序来处理事件。

I'm able to add an onClickevent handler via JavaScript as follows and it works fine:

我可以onClick通过 JavaScript添加一个事件处理程序,如下所示,它工作正常:

iframe.document.addEventListener('click', clic, false);

But in this case I'm unable to pass a parameter to clic(). I tried to print this.idin clic()but no result.

但在这种情况下,我无法将参数传递给clic(). 我试图打印this.idclic(),但没有结果。

onClickHTML attribute does not work at all, the handler is not called.

onClickHTML 属性根本不起作用,不调用处理程序。

<html>
<head>
<script type="text/javascript">
function def() {
    myFrame.document.designMode = 'on';
}
function clic(id) {
    alert(id);
}
</script>
</head>
<body onLoad="def()">
<iframe id="myFrame" border="0" onClick="clic(this.id)"></iframe>
</body></html>

采纳答案by Wladimir Palant

You can use closures to pass parameters:

您可以使用闭包来传递参数:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

但是,我建议您使用更好的方法来访问您的框架(我只能假设您正在使用 DOM0 方式通过它们的名称访问框架窗口 - 这只是为了向后兼容而保留的):

document.getElementById("myFrame").contentDocument.addEventListener(...);

回答by Gaurav Agrawal

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

iframe 没有 onclick 事件,但我们可以通过使用 iframe 的 onload 事件和这样的 javascript 来实现这一点......

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

希望对你有帮助......