The following code below works fine:
$("#searchTab").click(function(){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$(this).addClass("tabYes");
$(".content").hide();
$("#searchContent").show();
});
but if I try to organize the code into a function like below it does not work. Only "$(".content").hide();" from the function seem to work. Why is that?
function tabSelect(){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$(this).addClass("tabYes");
$(".content").hide();
}
$("#searchTab").click(function(){
tabSelect();
开发者_如何学Python $("#searchContent").show();
});
The this
reference has changed. You'll need to pass it as an argument to tabSelect
, or wrap it and use the wrapper. ($(this)
)
function tabSelect($itemToTab){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$itemToTab.addClass("tabYes");
$(".content").hide();
}
$("#searchTab").click(function(){
tabSelect($(this));
$("#searchContent").show();
});
Change this:
tabSelect();
to this:
tabSelect.call( this );
This manually sets the value of this
in the calling context of tabSelect()
.
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();
});
精彩评论