When to use $ and when not to use

I selected the control using the following variable

var txt = $("#text1");

Now, when I have to handle events in a text field, I need to refer to it as $ (txt), or txt will do

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

or

txt.keydown(function(){})

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

+4
source share
4 answers

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

+17
source

- , , . , , jQuery $

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

.

$() document.getElementById().

. . , (), .

0

In my experience, I have found that using $ (txt) gives more predictable results than assigning it as a reference anse using a link to call the same methods / properties. It may be superstition on my part, however, some of us at work were ripped off using a link such as txt rather than implicit $ (txt) when txt was assigned.

0
source

All Articles