【问题标题】:Cannot remove or add class using jQuery无法使用 jQuery 删除或添加类
【发布时间】:2013-09-09 11:15:44
【问题描述】:
我正在尝试在元素上操作切换类,但由于脚本正在运行其他功能并且正在对类名进行操作,因此无法使用切换类工具。因此我使用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/
感谢您提供的任何帮助
【问题讨论】:
标签:
javascript
jquery
addclass
removeclass
【解决方案1】:
试试
$(".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
【解决方案2】:
这是因为页面加载时没有view-followers-on类的元素,所以jQuery找不到目标元素,你应该委托事件,但我建议添加另一个类并使用toggleClass方法(如果您使用 2 个处理程序仅用于添加和删除类):
$(".follow").on('click', function(){
$(this).toggleClass("view-followers view-followers-on");
});
通常不需要切换2个类,使用一个类就足够了。
【解决方案3】:
第一次执行脚本时将附加点击处理程序。这意味着具有“view-followers-on”类的元素还不存在。它们附加到元素本身,这就是为什么只调用第一个处理程序。
【解决方案4】:
它有效,但问题是您必须为“-on”重新分配处理程序并删除处理程序以关闭。最好为处理程序使用一个额外的类来检查当前状态并替换状态。
【解决方案5】:
此函数查找两个类中的任何一个,view-followers 或 view-followers-on。
如果检测到其中任何一个,它将切换选择器上的两个类,本质上是切换应用于元素的类。
这也适用于动态元素,因为它使用事件委托来检测页面加载后创建的元素。
$(document).on('click', '.view-followers,.view-followers-on', function(){
$(this).toggleClass("view-followers view-followers-on");
});
【解决方案6】:
使用 togleClass() 函数,它将调用替代方法
$(".view-followers, .view-followers-on").click(function(){
$(this).toggleClass("view-followers view-followers-on");
})
;