Is storing jQuery elements in variables more efficient?

后端 未结 5 605
悲&欢浪女
悲&欢浪女 2021-01-05 00:20

Which is more efficient please?

var myElement = $(\"#the-name-of-my-element\")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSometh         


        
5条回答
  •  花落未央
    2021-01-05 01:04

    If you are doing multiple tasks with same element than it's better to cache it to variable so JS will not re-select element on every call.

    Also it's easier to maintain your code - e.g. if you want to change selector, than you have to change it in one place instead of going through code and searching for it.

提交回复
热议问题