Is storing jQuery elements in variables more efficient?

后端 未结 5 603
悲&欢浪女
悲&欢浪女 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 00:46

    It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).

    So the winner is:

    var myElement = $("#the-name-of-my-element")
    
    myElement.doSomethingOnce;
    myElement.doSomethingTwice;
    ...
    myElement.doSomethingTenTimes;
    

提交回复
热议问题