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

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

问题描述

我想使用以 iframe 的 id 作为参数的处理程序来处理 iframe 上的 click 事件.

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

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

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(...);

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

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