Define an event on iFrame element with jQuery

后端 未结 6 2060
Happy的楠姐
Happy的楠姐 2020-12-18 09:19

I try to define a live event on img tags store on a iFrame. For example, I would like obtain a simple javascript alert box when I click a image on my iFrame.

Do you

6条回答
  •  渐次进展
    2020-12-18 10:04

    jQuery.bind() won't work with external documents. At least in jQuery 1.6.2.

    However you can bind to DOM events:

    $("iframe").contents().find("img").onclick = function() { // do your staff here };
    

    If you do not have full list of images at the moment, you can use events propogation:

    $("iframe").contents().find("body").onclick = function() { // do your staff here };
    

    It will work event with custom events:

    $("iframe").contents().find("body").onmyevent = function() { // do your staff here };
    

    One more thing to remember... frame content is loaded asynchronously. So bind your handlers AFTER your iframe content is loaded:

    var $iframe = $("iframe"); 
    $iframe.bind("load", null, funcion(e) {
        $iframe.contents().find("body").onclick = function() { // do your staff here }; 
    });
    

    For more complicated cases handle your images clicks inside iframe, and trigger your custom events that you can later handle on the body level. Especially if you have totally dynamic content and want to bind to 'live' events inside iframe.

提交回复
热议问题