Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?

后端 未结 3 732
花落未央
花落未央 2021-01-13 02:55
$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)

Is it a better practice to do this:

var p         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 03:41

    Yes it does, when you use the selector without storing it in a variable jQuery needs to parse the DOM EVERY TIME.

    If you had something like $(".class") jQuery would need to find the elements with that class every time you use it but if it is stored in a variable it uses the unique identifier in the variable. No need to lookup.

    So yeah i would totally recommend storing it into a variable.

    UPDATE: Added chaining as an alternative.

    If you only use the selector in one place you can also do chaining which means you add one method after another with the same dot notation like this:

    $(".class")
           .click(function(){ ... })
           .mouseenter(function(){ ... })
           .css( ... );
    

提交回复
热议问题