2011-06-21 41 views
3

下面的下面的代碼工作正常:不能得到與jQuery函數工作

$("#searchTab").click(function(){ 
$(".tab").addClass("tabNo"); 
$(".tab").removeClass("tabYes"); 
$(this).addClass("tabYes"); 
$(".content").hide(); 
$("#searchContent").show(); 
}); 

但如果我嘗試將代碼組織成一個功能類似下面這是行不通的。只有「$(」。content「)。hide();」從功能上看似乎奏效。這是爲什麼?

function tabSelect(){ 
$(".tab").addClass("tabNo"); 
$(".tab").removeClass("tabYes"); 
$(this).addClass("tabYes"); 
$(".content").hide(); 
} 

$("#searchTab").click(function(){ 
    tabSelect(); 
    $("#searchContent").show(); 
}); 
+2

使用'this'作爲元素的引用不再有效。你需要將它作爲參數傳遞......(或者使用patrick dw顯示的'call',很好!) –

回答

7

this參考文獻已更改。您需要將它作爲參數傳遞給tabSelect,或者將其包裝並使用包裝器。 ($(this)

function tabSelect($itemToTab){ 
$(".tab").addClass("tabNo"); 
$(".tab").removeClass("tabYes"); 
$itemToTab.addClass("tabYes"); 
$(".content").hide(); 
} 

$("#searchTab").click(function(){ 
    tabSelect($(this)); 
    $("#searchContent").show(); 
}); 
+0

正確。函數內的$(this)引用函數對象,在click函數中引用被單擊的元素。 –

4

更改此:

tabSelect(); 

這樣:

tabSelect.call(this); 

此手動設置的thistabSelect()調用上下文值。

function tabSelect(){ 
    $(".tab").addClass("tabNo").removeClass("tabYes"); // chain these! 
    $(this).addClass("tabYes"); // now "this" is the element you're expecting 
    $(".content").hide(); 
} 

$("#searchTab").click(function(){ 
    tabSelect.call(this); // set "this" in the calling context of "tabSelect" 
          // to the current value of "this" (the element) 
    $("#searchContent").show(); 
});