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

查看:255
本文介绍了如何使用JQuery将click事件添加到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:

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

我似乎无法获得任何变化。想法?

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

推荐答案

iframe没有'onclick'事件,但您可以尝试捕获文档中的click事件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");
}

编辑
虽然这不是'解决您的跨站点问题,FYI 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) { });

2015年1月更新
iframe解释的链接已被删除,因为它已不再可用。

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将click事件添加到iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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