In jQuery, is it faster to check if an element exists before trying to bind event handlers?

前端 未结 4 566
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 03:38

Is it faster to first check if an element exists, and then bind event handlers, like this:

if( $(\'.selector\').length ) {
    $(\'.selector\').on(\'click\',         


        
4条回答
  •  别那么骄傲
    2020-12-20 04:28

    Use the binding directly.

    $('selector').on('click',function() {
        // Do stuff on click
    }
    

    If if there are no elements with the specified selector, it won't do anything - not even post an error, which means that actual check for the element would be doing the same thing twice. I wouldn't call it exactly a check of the existence of an element, but the way this is implemented in jQuery certainly acts that way.

提交回复
热议问题