2011-06-21 42 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(); 
});