2016-11-15 79 views
0

在我的示例工作中,我想從我的html元素的任何位置檢測單擊事件。當我點擊直接html而不是iFrames - 所以我想從我的window的任何地方聽到。使用jQuery做正確的方法是什麼?如何檢測HTML中包含iFrame的任何地方的點擊事件?

即使我也想從動態htmls聽到。 (我的情況下,有與數字

here is the demo循環

我的代碼:

var findAllClicks = function() { 
    $(document).on('click', '*', function() { 
    console.log($(this)[0]); //only works on direct html element. 
    }) 
} 

var outsideFunction = function() { 
    console.log('loop ends'); 
} 

outsideFunction(); 

$(function() { 
    //finding click events from any where. 
    findAllClicks(); 
    var total = 1000; 
    var i = 0; 
    var iterate = function() { 
    setTimeout(function() { 
     var place = $('#iFrame1').contents().find('#iFrame2').contents().find('body'); 
     place.append('<ul class="list"></ul>'); 
     for (i = 0; i < total; i++) { 
     place.find('.list').append('<li>' + i + '</li>'); 
     } 
    }, 3000); 
    //how to find all this done from outside of this function? 
    } 

    var iFrame1 = $('<iframe />', { 
    id: 'iFrame1' 
    }); 

    var iFrame2 = $('<iframe />', { 
    id: 'iFrame2' 
    }); 

    var button2 = $('<button />', { 
    text: 'Child Button', 
    click: iterate 
    }); 

    var button = $('<button />', { 
    text: 'Click Me', 
    click: function() { 
     $(this).parents('body').append(iFrame2); 
     $('#iFrame1').contents().find('#iFrame2').contents().find('body').append(button2); 
    } 
    }); 


    setTimeout(function() { 
    $('.container').append(iFrame1); 
    $('#iFrame1').contents().find('body').append(button); 
    }, 1000); 
}); 

回答

0

很抱歉,如果我誤解了,但如果你只是想記錄的點擊數在窗口上,你可以使用

window.onclick = function() {count++;console.log(count);}; 
相關問題