2011-06-21 17 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のshow、nice!と '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)は関数オブジェクトを参照し、クリック関数はクリックされた要素を参照していた。 –

4

変更これ:これ

tabSelect(); 

tabSelect.call(this); 

これは手動tabSelect()の呼び出しコンテキストでthisの値を設定します。

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(); 
});