简体   繁体   中英

$element.click vs $('element').click

I am trying to optimize parts of my code, I'd like to know which one of the following should I use and why, what is the benefit of one over the other?

$('element').click(function() { /* do something */ })

or

let $element = $('element')
$element.click(function() { /* do something */ })

The only difference between them is that in the second one, you have a variable that has a reference to the jQuery object, which you could reuse. You only need that if you want to reuse it, eg:

let $element = $("element");
$element.click(function() { /* ... */ });
if (someCondition) {
    $element.addClass("whatever");
} else {
    $element.find("some-child").remove();
}
// ...

Repeating the $("element") part in the above would be a bit more typing, and would require looking up the element(s) in the DOM repeatedly and creating new jQuery objects repeatedly, which would be less efficient than reusing the same object.

Sometimes you don't need a variable, since jQuery's API is designed for chaining. (Which is why I threw in the if above, so I could just do $("element").click(/*...*/).addClass(/*...*/).find(/*...*/) etc.)

It depends on one question mainly for me - will I use that selector again?

If the answer is yes, then yes, define the variable to use and use it for the .on function and wherever else, if it's only once, then it uses more characters to define it and use it then to just use it. But there's no huge difference (unless you opt with method 1 and reuse selectors throughout)

if the element is referred one or two times means option1 is better. but if the element is referred multiple times means options 2 is better because you are diving into the dom only once even though it is referred multiple times and it will improve the performance and good coding practice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM