When to use "$" in javascript / jQuery

Recently, I am starting to do javascript and jQuery, and one thing that I constantly ask myself is when to use "$", I know what points to jQuery, but it does not always seem like that. I will give some examples:

These are the two scripts I wrote:

Firstly:

$(function() {
    var newHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;">Login</span>';
    var oldHTML = '<span style="font-size: 32px; line-height: 18px;">+</span><span style="font-size: 14px; float: left;">Add to watchlist</span>';

    // on mouse over
    $("a.bid-addwatchlist").hover(
    function () {
        (this).innerHTML = newHTML;
    },
    // on mouse out
    function () {
        (this).innerHTML = oldHTML;
    });
});

Second:

(function(){
    $("#container a").click(function(){
        if ($(this).html() == "Stop Listening")
        {
            $(this).html("Listen");
        }
        else if ($(this).html() == "Listen")
        {
            $(this).html("Stop Listening");
        }
    });
});

Why doesn't this work in the first script if I have $ before "this" and a second script is needed?

Note: I already looked here: When to use $ and when not to

But this answer was not complete enough.

+5
source share
5 answers
$(function(){
  // ...
});

is equivalent to:

$(document).ready(function () {
  // ...
});

, jQuery .

, , :

(function(){
  // ...
});

:

(function(){
  // ...
})();

.

script $(this), jQuery . , , , , .

+10

$, jQuery, . DOM, DOM , , jQuery. , jQuery, jQuery, , , jQuery .

:

$("#myButton").blur(function() {
    if (!this.value) {
        this.value = "Enter name";
    }
});

, script jQuery, .

javascript , jQuery. :

$("#myButton").blur(function() {
    if (!$(this).val()) {
        $(this).val("Enter name");
    }
});

jQuery . .

... , , . , jQuery .

+2

JQuery DOM. "$ (this)", . , JQuery.

"this", DOM, . DOM JQuery ( JQuery!)

, JQuery DOM, . , JQuery , DOM.

EDIT: DOM Document Object Model. , , ( DOM). , document.getElementById( "anId" ) " DOM" . . , DOM - , . "innerHTML". JQuery DOM,

+2

jquery

jQuery.fn = jQuery.prototype = {

    ....

    // HANDLE: $(expr, context)
            // (which is just equivalent to: $(context).find(expr)
            } else {
                return this.constructor( context ).find( selector );
            }

        // HANDLE: $(function)
        // Shortcut for document ready
        } else if ( jQuery.isFunction( selector ) ) {
            return rootjQuery.ready( selector );
        }

        if (selector.selector !== undefined) {
            this.selector = selector.selector;
            this.context = selector.context;
        }

        return jQuery.makeArray( selector, this );

    ....

}

$() DOM, DOM , .

() , , ()() ;

+1

this DOM, . innerHtml.

DOM jQuery jQuery, .html(), , innerHtml.

+1

All Articles