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

前端 未结 4 562
没有蜡笔的小新
没有蜡笔的小新 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:21

    Just use

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

    If no elements exist with the class selector, jQuery will simply not bind anything.

提交回复
热议问题