无法使用jQuery删除或添加类

时间:2013-09-09 11:15:45

标签: javascript jquery addclass removeclass

我正在尝试在元素上操作切换类但不能使用toggleClass工具,因为脚本正在运行其他函数并且正在对类名进行操作。因此我使用removeClass / addClass。出于某种原因,我无法让它发挥作用。请在下面找到我的脚本;

$(".view-followers").click(function(){
    alert("off");
    $(this).removeClass("view-followers");
    $(this).addClass("view-followers-on");

});

$(".view-followers-on").click(function(){
    alert("on");
    $(this).removeClass("view-followers-on");
    $(this).addClass("view-followers");
});

或者你可以在jsFiddle上查看; http://jsfiddle.net/dannyj6/UGBda/

感谢您提供的任何帮助

6 个答案:

答案 0 :(得分:4)

尝试

$(".view-followers, .view-followers-on").click(function(){
    $(this).toggleClass("view-followers view-followers-on");
});

演示:Fiddle

如果你想拥有两个独立的处理程序,那么使用事件委托

$(document).on('click', '.view-followers', function(){
    $(this).removeClass("view-followers").addClass("view-followers-on");

});
$(document).on('click', '.view-followers-on', function(){
    $(this).removeClass("view-followers-on").addClass("view-followers");
});

演示:Fiddle

答案 1 :(得分:3)

那是因为当加载页面时没有类view-followers-on的元素,所以jQuery找不到目标元素,你应该委托事件,但我建议添加另一个类并使用{{ 1}}方法(如果您使用2个处理程序只是为了添加和删除类):

toggleClass

通常不需要切换2个类,使用一个类就足够了。

答案 2 :(得分:1)

首次执行脚本时,将附加点击处理程序。这意味着具有“view-followers-on”类的元素尚不存在。它们附加到元素本身,这就是为什么只调用第一个处理程序。

答案 3 :(得分:0)

它有效,但问题是你必须重新分配" -on"并删除处理程序关闭。最好为处理程序使用额外的类来检查当前状态并替换状态。

答案 4 :(得分:0)

此函数查找两个类中的任何一个,视图跟随者或视图跟随者。

如果检测到其中任何一个,它将切换选择器上的两个类,基本上切换应用于元素的类。

这也适用于动态元素,因为它使用事件委托来检测页面加载后创建的元素。

$(document).on('click', '.view-followers,.view-followers-on', function(){
    $(this).toggleClass("view-followers view-followers-on"); 
});

答案 5 :(得分:0)

使用toogleClass()函数,它将调用替代

$(".view-followers, .view-followers-on").click(function(){
    $(this).toggleClass("view-followers view-followers-on");
})