0

我正在尝试在元素上操作切换类,但不能使用切换类工具,因为脚本正在运行其他函数并且正在对类名进行操作。因此我使用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/

感谢您提供任何帮助

4

6 回答 6

4

尝试

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

演示:小提琴

如果您想拥有两个单独的处理程序,请使用事件委托

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

演示:小提琴

于 2013-09-09T11:18:29.307 回答
3

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

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

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

于 2013-09-09T11:19:26.763 回答
1

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

于 2013-09-09T11:20:15.220 回答
0

它可以工作,但问题是您必须为“-on”重新分配处理程序并删除处理程序以关闭。最好为处理程序使用一个额外的类来检查当前状态并替换状态。

于 2013-09-09T11:19:26.627 回答
0

此函数查找两个类中的任何一个,view-followers 或 view-followers-on。

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

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

$(document).on('click', '.view-followers,.view-followers-on', function(){
    $(this).toggleClass("view-followers view-followers-on"); 
});
于 2013-09-09T11:25:01.430 回答
0

使用将调用替代的工具类()函数

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

;

于 2013-09-09T11:32:16.047 回答