Javascript 无法使用jQuery删除或添加类
我试图在元素上操作toggle类,但无法使用toggleClass工具,因为脚本正在运行其他函数,并且正在对类名执行操作。因此,我使用removeClass/addClass。由于某种原因,我不能让它工作。请在下面找到我的脚本Javascript 无法使用jQuery删除或添加类,javascript,jquery,addclass,removeclass,Javascript,Jquery,Addclass,Removeclass,我试图在元素上操作toggle类,但无法使用toggleClass工具,因为脚本正在运行其他函数,并且正在对类名执行操作。因此,我使用removeClass/addClass。由于某种原因,我不能让它工作。请在下面找到我的脚本 $(".view-followers").click(function(){ alert("off"); $(this).removeClass("view-followers"); $(this).addClass("view-followers
$(".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");
});
或者您可以在JSFIDLE上查看;
感谢您提供的任何帮助请尝试
$(".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");
});
演示:它可以工作,但问题是您必须为“-on”重新分配处理程序,并删除“off”处理程序。可能最好为处理程序使用一个额外的类,用于检查当前状态并替换状态。这是因为加载页面时,页面上没有类为
的元素查看跟随者,因此jQuery无法找到目标元素,您应该委派事件,但我建议添加另一个类并使用toggleClass
方法(如果您使用2个处理程序来添加和删除类):
通常不需要切换两个类,使用一个类就足够了 第一次执行脚本时,将附加单击处理程序。这意味着类为“view followers on”的元素尚不存在。它们被附加到元素本身,这就是为什么只调用第一个处理程序。此函数查找两个类中的任何一个,查看跟随者或上的查看跟随者
如果检测到其中任何一个,它将切换选择器上的两个类,实质上切换应用于元素的类
这也适用于动态元素,因为它使用事件委派来检测页面加载后创建的元素
$(document).on('click', '.view-followers,.view-followers-on', function(){
$(this).toggleClass("view-followers view-followers-on");
});
使用toogleClass()函数,它将调用alternative
$(".view-followers, .view-followers-on").click(function(){
$(this).toggleClass("view-followers view-followers-on");
})
) 足够近:修复。。。谢谢大家。。
$(".view-followers, .view-followers-on").click(function(){
$(this).toggleClass("view-followers view-followers-on");
})