将Click事件处理程序添加到iframe [英] Adding click event handler to iframe

查看:133
本文介绍了将Click事件处理程序添加到iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 iframe 上使用获取的处理程序处理点击事件iframe 将id作为参数。

I want to handle click event on an iframe with a handler that gets the iframe’s id as parameter.

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

I’m able to add an onClick event handler via JavaScript as follows and it works fine:

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

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

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

onClick HTML属性根本不起作用,不会调用处理程序。

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

<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>


推荐答案

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

You can use closures to pass parameters:

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

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

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):

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

这篇关于将Click事件处理程序添加到iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆