The embarrassment of saving a variable using the $ () function

In jQuery, if I do this:

var a = $("#someid"); 

Now that I need to continue the link using jQuery, what should I do?

 $(a).attr("id"); 

or

 a.attr("id"); 

I test things, and I'm confused, I just want an official word so I can rule it out.

+4
source share
3 answers

This:

 a.attr("id"); 

since a already a jQuery object.

Although this is a convention used by many for prefix variables that reference a jQuery object using $ .

So:

 var $a = $("#someid"); $a.attr("id"); 

This is only a general agreement, not a requirement. I think this adds clarity, but it can only be because I have long been used to looking for $ .

+9
source

Both will work, but $(a) will have no effect, so this is a function call in vain.

+3
source

Using your example, the second option is correct.

 var a = $("#someid"); a.attr("id"); 

You can also use the first parameter, but since a already a jquery object, it is pointless.

0
source

Source: https://habr.com/ru/post/1334575/


All Articles