Most efficient way to re-use jQuery-selected elements

后端 未结 4 2392
南方客
南方客 2021-02-20 17:14

I can imagine the correct answer to this based on theory, but I\'m just looking for some confirmation. I\'m wondering what the most efficient way to re-use a jQuery-selected ele

4条回答
  •  耶瑟儿~
    2021-02-20 17:28

    This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.

    $('a').click(function(){
      var $this = $(this);
      $this.addClass("clicked");
      $this.attr("clicked", true);
    });
    

提交回复
热议问题