如何使用 JQuery 将点击事件添加到 iframe [英] How to add click event to a iframe with JQuery

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

问题描述

我在页面上有一个 iframe,来自第三方(广告).我想在点击 iframe 时触发点击事件(记录一些内部统计数据).类似的东西:

I have an iframe on a page, coming from a 3rd party (an ad). I'd like to fire a click event when that iframe is clicked in (to record some in-house stats). Something like:

$('#iframe_id').click(function() {
    //run function that records clicks
});

..基于 HTML 的:

..based on HTML of:

<iframe id="iframe_id" src="http://something.com"></iframe>

我似乎无法让任何变体起作用.想法?

I can't seem to get any variation of this to work. Thoughts?

推荐答案

iframe 没有 'onclick' 事件,但您可以尝试在 iframe 中捕捉文档的点击事件:

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

编辑虽然这不能解决您的跨站点问题,但仅供参考 jQuery 已更新,可以与 iFrames 配合使用:

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

$('#iframe_id').on('click', function(event) { });

更新 1/2015iframe 说明的链接已被删除,因为它不再可用.

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

注意如果 iframe 来自与主机页面不同的域,则上面的代码将不起作用.您仍然可以尝试使用评论中提到的技巧.

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

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

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