开发者

This difference [duplicate]

This question already has answers here: 开发者_高级运维 Closed 11 years ago.

Possible Duplicate:

jQuery $(this) vs this

This code in this video Tutorial

in a Very useful blog jquery for designers

$('.navigation').each(function () {
    var $links = $('a',this);
    $links.click(function  () {
        var $link = $(this),
            link = this;
            if ($link.is('.selected')) {
                return;
        }
        $links.removeClass('selected');
        $link.addClass('selected')
    });
});

What is the difference between $(this) and this?

Please explain the simple difference in coding.


Within the handler being pased into click, this will refer to the DOM element that the click handler was attached to. Calling $() on it ($(this)) wraps that up in a jQuery instance, making various jQuery functions available to you.

In your quoted code, the link = this line is unnecessary as nothing ever uses link. The $link = $(this) line, though, creates a jQuery wrapper around the link so you can use functions like is and addClass.


Off-topic

  1. You probably want to change if ($link.is('.selected')) to if ($link.hasClass('selected')) so that jQuery doesn't have to parse the CSS selector.
  2. You have a typo, the "o" in removeClass is missing.


this is native JavaScript that references the current object in scope. $(this) is jQuery wrapped (adding additional properties) to that priormentioned object. Examples:

Plain JS

var person = {
    SayGoodbye: function(){
        this.wave();
        this.exit();
    },
    wave: function(){
        //code to wave
    },
    exit: function(){
        //code to exit
    }
}

person.SayGoodbye();

Some jQuery

//a submit button
$('#myBtn').click(function(){
    $(this).attr('disabled', true);
    $(this).text("Submitting...");
});


// get everything with the class navigation
$('.navigation').each(function () {
    // get all anchor tags in that context
    var $links = $('a',this);
    // assign a listener for the click event.
    $links.click(function  () {
        // set $link = jQuery wrapper around this
        var $link = $(this),
        // set link = this;
        link = this;
        // if the link has the selected class do nothing
        if ($link.is('.selected')) {
                return;
        }
        //otherwise remove it and then add it again???
        $links.remveClass('selected');
        $link.addClass('selected')
    }); // exit anchor loop
}); // exit nav. loop

P.S. the link variable is unused above.


'this' is the DOM element as accessible by normal JavaScript, whereas when you turn this into $(this), you are creating a JQuery object with more jQuery added API out of that DOM element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜