开发者

Best way to check element present before binding function in jQuery?

开发者 https://www.devze.com 2023-02-14 18:50 出处:网络
I\'ve been using the following test/function pair in an effort to only attach functions to appropriate page elements if one or more are present:

I've been using the following test/function pair in an effort to only attach functions to appropriate page elements if one or more are present:

function assistedSearch() {
    $('.assistedSearch').focus( function() {
        ...
    });
}
$(function() {
    if ( $('.assistedSearch').length > 0 ) {
        assistedSearch();
    }
});

function inputHinting() {
    $(':input.hint').each( func开发者_C百科tion() {
        ...
    });
}
$(function() {
    if ( $(':input.hint').length > 0 ) {
        inputHinting();
    }
});

Is this a classic case of over-engineering? Is the "if" test before each function binding unnecessary?

If it's not over-engineering, is there a less DOM-intensive way of ensuring only the required functions are bound to the current page?


By doing the method you propose you are actually losing performance since each if queries the dom and your function issues the query again.

function inputHinting() {
    $(':input.hint').each( function() { //query the dom again since it was found.
        ...
    });
}
$(function() {
    if ( $(':input.hint').length > 0 ) { //Query the dom for :input.hint
        inputHinting();
    }
});

jQuery will handle this for you as it makes sure the element is present before something is done to it. With that being said if you do this, you should cache your selectors like the following:

function inputHinting($inputHint) {
    $inputHint.each( function() { 
        ...
    });
}
$(function() {
    var $inputHint = $(':input.hint');
    if ( $inputHint.length > 0 ) { //Query the dom for :input.hint
        inputHinting($inputHint);
    }
});

By doing that you only query the dom once.


You shouldn't really care about that. Jquery checks internally so you don't have to worry about it. If you really must check it for some reason of your own, the .length property would be the way to go.

EDIT

Also, you don't need to do

if ( $(':input.hint').length > 0 ){}

Simply using the below is equivalent

if ( $(':input.hint').length) {} 


try this:

(function(elem)
{
    if(elem.length>0)
        elem.each( function() 
        {
            ...
        });
})($(':input.hint'));

So this will query the dom only once, then it will pass the jquery object collection to an anonymous function and execute it.

0

精彩评论

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