开发者

Confused about when saving a variable using the $() function

In jQuery, if I do this:

var a = $("#someid");

No开发者_StackOverflow中文版w when I need to further reference using jQuery, what should I be doing?

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

or

a.attr("id");

I'm testing things out and I'm getting confused, just want the official word so I can rule this out.


This one:

a.attr("id");

since a is already a jQuery object.

Although it is a convention used by many to prefix variables that reference a jQuery object with $.

So:

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

This is only a common convention, and not a requirement. I think it adds clarity, but that may be just because I'm pretty conditioned to look for the $ by now.


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


Using your example, the second option is correct.

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

You can use the first option too, but because a is already a jquery object, its pointless.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜