jquery events on non-present elements

后端 未结 2 794
小蘑菇
小蘑菇 2021-02-19 22:43

Is it bad to tie events to ids that aren\'t on the page in certain circumstances (based on PHP)? Will it cause code errors and slowness, or will jQuery automatically ignore them

2条回答
  •  忘掉有多难
    2021-02-19 23:06

    When jQuery selector doesn't return any elements, no events are being bound. So you're making no harm by not writing if statement.

    This means that internally jQuery binds event handler to all matched elements. When there are none, no handler will get bound to any element. This means: you don't have to check element existence in your code.

    Future reference

    Whenever you're doing

    if ( $('#element') ){
        $('#element').click(function(event) { /* blah blah */ });
    }
    

    you should rather save selector results

    var result = $('#element');
    
    // check number of elements (zero equals false, anything else equals true)
    if (result.length) {
        result.click(function(event) {
            // blah blah
        });
    }
    

    result.length is same as result.size().

    Binding event handlers to non existing elements

    If your interface will generate new elements and you'd like them to have eevent handlers attached when they get added to DOM, then you should use delegate() function. There's also live() function but use the first one whenever possible, because it is a better alternative. There are numerous resources on the net why this is true. This Stackoverflow answer for instance.

    Note: As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation.

    See jQuery documentation.

提交回复
热议问题