最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - When to use $ and when not to - Stack Overflow

programmeradmin3浏览0评论

I have selected a control using the following variable

var txt = $("#text1");

Now when I have to handle events on the textbox, do I have to reference it as $(txt) or txt will do

$(txt).keydown(function() {})

or

txt.keydown(function(){})

What is the advantage. Please explain it taking the variable txt as the context.

I have selected a control using the following variable

var txt = $("#text1");

Now when I have to handle events on the textbox, do I have to reference it as $(txt) or txt will do

$(txt).keydown(function() {})

or

txt.keydown(function(){})

What is the advantage. Please explain it taking the variable txt as the context.

Share Improve this question edited Oct 14, 2009 at 15:13 bdukes 156k25 gold badges150 silver badges176 bronze badges asked Oct 14, 2009 at 15:02 KJaiKJai 1,7053 gold badges15 silver badges16 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 17

If txt is already equal to a jquery object, there is no need to use $(txt) as it's just extra processing to return the same thing.

The best approach is to declare your variables so know what they are. Basically, what I'm saying is apply some apps hungarian and prefix your jQuery variables with a $

var $text1 = $("#text1");  // this is a jQuery object
var text1 = $text1[0];     // this is not

A bit more info on Chad's response.

The $() is a short cut to the monly used function document.getElementById().

Once you lookup and store the object's value you don't need to look it up again. As Chad mentioned. Ask your self is the variable an object or a name (string), if it's a name you will have to lookup the object.

In my experience I've found that using $(txt) yields more predictable results pared to assigning it as a reference ans using the reference to call the same methods/properties. It's possibly superstition on my part, however a few of us at work have been foiled by using a reference such as txt rather than an implicit $(txt) once txt has been assigned.

发布评论

评论列表(0)

  1. 暂无评论