在下面的第6行,我有$("ul.tabrow li").removeClass("active"); //Remove any "active" class
如果我将其更改为使用$(this).removeClass("active")
,那么它就不会像我想象的那样有效。
代码实现了我现在想要的方式,我只是想知道为什么我上面提到的不起作用,在下面的第7行我使用$(this)
看似相同的选择器和那个适用于第7行的代码,但在第6行有所不同。
任何人都能解释一下吗?
$("ul.tabrow li").bind({
click: function() {
return false;
},
mouseenter: function() {
$("ul.tabrow li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab-box").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
//$(activeTab).fadeIn(); //Fade in the active content
$(activeTab).show(); //Fade in the active content
return false;
}
});
答案 0 :(得分:7)
您实际上希望在第6行使用$("ul.tabrow li")
。这是因为$(this)
仅引用当前列表项,而不是所有列表项。
$(this)
不是选择器的替代品,它指的是当前活动元素(您将鼠标悬停在其上)。因此,在第六行使用this
会从当前元素中删除活动类,然后立即将其添加回来。结果基本上没有发生。
如果你不想重复选择器,那么你可能想要使用更通用的东西,比如
$(this).siblings().removeClass('active');