2011-06-06 97 views
-1

可能重複:
jQuery $(this) vs this這種差異

這段代碼在此video Tutorial

在一個非常有用的博客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') 
    }); 
}); 

$(this)this有什麼區別?

請解釋簡單的編碼差異。

回答

8

在被裝入click的處理程序中,this將引用點擊處理程序所連接的DOM元素。調用$()就可以了($(this))將它包裝在一個jQuery實例中,爲您提供各種jQuery函數。

在你的引述代碼中,link = this行是不必要的,因爲沒有任何東西使用link。但是,$link = $(this)行會在鏈接周圍創建一個jQuery包裝器,因此您可以使用isaddClass之類的函數。


題外話

  1. 你可能想改變if ($link.is('.selected'))if ($link.hasClass('selected')),這樣的jQuery不必解析CSS選擇器。
  2. 您有一個錯字,缺少removeClass中的「o」。
+2

+1兩個代碼提示。這些很容易錯過。 – cwallenpoole 2011-06-06 16:03:47

+0

謝謝@ T.j。 Crowder – tito11 2011-06-06 16:05:50

1

this是原生JavaScript,參考scope中的當前object$(this)是將jQuery包裝(添加其他屬性)到前面提到的對象。例子:

平原JS

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

person.SayGoodbye(); 

一些jQuery的

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

謝謝@pixelbobby – tito11 2011-06-06 16:08:49

1
// 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 

附:鏈接變量未在上面使用。

+0

非常感謝,是的,因爲這只是代碼的一部分 – tito11 2011-06-06 16:17:34

0

'this'是可以通過普通JavaScript訪問的DOM元素,而當您將此元素變爲$(this)時,您將創建一個JQuery對象,其中包含更多jQuery的JQuery對象將API添加到該DOM元素之外。