Track clicks inside iframe with Jquery

一世执手 提交于 2019-12-23 03:44:33

问题


I'm trying to figure out a way of tracking clicks inside an iframe with jquery. The iframe is locate on the same domain but still I don't seem to be able to make this work, here's my code:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
    var clicks = 0;
    $('#myframe').load(function() {
        alert('loaded');
        var that = $(this);
        that.contents().find('a').bind('click', function(e) {
            e.preventDefault();
            clicks++;
            $('#clicks').html(clicks);
        });
    });
</script>
</head>
<body>
Clicks: <span id="clicks" >0</span>
<iframe id="myframe" src="test_iframe.php" width="500" height="500"></iframe>
</body>
</html>

Any idea of what could be wrong ?

I've saw other questions very similar to this one at SO but none of the answers solved my problem.

UPDATE:

I've updated my code at http://www.politicos.biz/stack/iframe_click.php with @Wes code, it works on jsfiddle but not on my site.


回答1:


Make sure that the iframe is fully loaded befor you add the event.

I would expect the handler to be added with .document

$('body', window.parent.frames[0].document).click( 
    function(){} 
);

OR

$('body', $('templateframe')[0].document).click( 
    function(){} 
);



回答2:


Here is an example:

http://jsfiddle.net/wesbos/VxA8t/1/

$(function() {
    var clicks = 0;
    $('#myframe').contents().find('a').bind('click', function(e) {
        e.preventDefault();
        clicks++;
        $('#clicks').html(clicks);
    });
});

You need to find the link first and then bind to it.

Your code should be something like this:

$('body', $('templateframe')).contents().find('a').click(function(event) {
  alert("Link Clicked");
});



回答3:


on the parent frame, create a function to be called from inside the iframe.

parent:

var click = 0;
function addClick()
{
    click++;
}

then, call it from the iframe

parent.addClick();

finally, simple refer to click for the number of click count. Hope this helps.



来源:https://stackoverflow.com/questions/7170698/track-clicks-inside-iframe-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!