在 jQuery 中切换 class 切换而不是追加
Toggle class in jQuery switching rather than appending
我正在尝试将 class 添加到名为 'activetab' 的点击元素。
我怎样才能做到这一点,如果您单击 tab2,您将添加 class,但是如果您单击 tab3,它将从选项卡 2 移到选项卡 3 上,依此类推。目前它只是附加它。
$(".tab2").click(function () {
$(".tab2").addClass("activetab");
});
$(".tab3").click(function () {
$(".tab3").addClass("activetab");
});
$(".tab4").click(function () {
$(".tab4").addClass("activetab");
});
您可以使用 removeClass()
删除 class。此外,所有处理程序都可以组合成一个处理程序,它将 activetab
class 添加到单击的选项卡并将其从其他选项卡中删除。
// Bind click event on all the tabs
$(".tab2, .tab3, .tab4").click(function () {
// Remove class from other tab
$(".activetab").removeClass('activetab');
// Add class to the current clicked tab
$(this).addClass("activetab");
});
我正在尝试将 class 添加到名为 'activetab' 的点击元素。 我怎样才能做到这一点,如果您单击 tab2,您将添加 class,但是如果您单击 tab3,它将从选项卡 2 移到选项卡 3 上,依此类推。目前它只是附加它。
$(".tab2").click(function () {
$(".tab2").addClass("activetab");
});
$(".tab3").click(function () {
$(".tab3").addClass("activetab");
});
$(".tab4").click(function () {
$(".tab4").addClass("activetab");
});
您可以使用 removeClass()
删除 class。此外,所有处理程序都可以组合成一个处理程序,它将 activetab
class 添加到单击的选项卡并将其从其他选项卡中删除。
// Bind click event on all the tabs
$(".tab2, .tab3, .tab4").click(function () {
// Remove class from other tab
$(".activetab").removeClass('activetab');
// Add class to the current clicked tab
$(this).addClass("activetab");
});