开发者

jQuery Test if DOM Element Supports "load" Event

开发者 https://www.devze.com 2023-03-12 10:45 出处:网络
Is it possible to check if a jQuery object supports firing an event handler for a specific event? I have a function that 开发者_如何转开发takes a DOM element and I want to listen for \"load\" to fade

Is it possible to check if a jQuery object supports firing an event handler for a specific event? I have a function that 开发者_如何转开发takes a DOM element and I want to listen for "load" to fade in the element using the following:

element.css({ opacity: 0.0 });
element.bind('load', function() { $(this).animate({ opacity: 1.0 }); });

Unfortunately, this fails if the passed in element is not an image (as it will always be transparent). Thanks!


jQuery can bind the 'load' event to any DOM element (<== This never fails). However, that event does not fire at any DOM element (It fires at window, document, scripts, stylesheets, images, iframes, etc.).

If the 'load' event does not fire at a given element (for instance, a DIV), then there is no point in binding a load handler to that element.


Since my comment seemed to be an acceptable route, here's a more complete answer:

Since it would seem that your function will only work if the passed element is an image, simply test to see if the element passed in is an image:

function conditional(element) {
    if(element.tagName == "IMG") {
        element.css({ opacity: 0.0 }).bind('load', function() { $(this).animate({opacity: 1.0 }); });
    }
}

http://jsfiddle.net/cHsMx/2/

0

精彩评论

暂无评论...
验证码 换一张
取 消