Is storing jQuery elements in variables more efficient?

后端 未结 5 606
悲&欢浪女
悲&欢浪女 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:03

    jQuery does not cache selectors - as detailed in this question:

    Does jQuery do any kind of caching of "selectors"?

    As a result, each time you perform $("#the-name-of-my-element") jQuery is performing some work to match the selector.

    For anything other than trivial code, I'd always cache selectors.

    See also ...

    At what level should I cache results of jQuery DOM queries?

提交回复
热议问题