Performance of jQuery selectors vs local variables

后端 未结 5 1411
清歌不尽
清歌不尽 2020-12-03 07:24

Is it recommended that, when I need to access the result of a jQuery selector more than once in the scope of a function, that I run the selector once and assign it to a loca

5条回答
  •  佛祖请我去吃肉
    2020-12-03 08:08

    Another option here is to use an each instead of repeating the selector, and it's associated work, time and time again

    var execute = function(){
        $('.myElement').each(function() {
          var elem = $(this);
          elem.css('color','green');
          elem.attr('title','My Element');
          elem.click(function(){
            console.log('clicked');
          });
        });
    }
    

提交回复
热议问题