Javascript添加和删除类不起作用
我尝试构建显示和隐藏导航以节省更多空间。但毕竟我这么做了,它变得很紧张。我可以删除show类并添加hide类,但之后hide类什么也不做。请帮忙Javascript添加和删除类不起作用,javascript,jquery,css,Javascript,Jquery,Css,我尝试构建显示和隐藏导航以节省更多空间。但毕竟我这么做了,它变得很紧张。我可以删除show类并添加hide类,但之后hide类什么也不做。请帮忙 <script> $(".servicesShowLink").click(function(){ document.getElementById("servicesShow").className = ""; document.getElementById("servicesShow
<script>
$(".servicesShowLink").click(function(){
document.getElementById("servicesShow").className = "";
document.getElementById("servicesShow").className = "servicesHideLink";
});
$(".servicesHideLink").click(function(){
document.getElementById("servicesShow").className = "";
document.getElementById("servicesShow").className = "servicesShowLink";
});
</script>
$(“.servicesShowLink”)。单击(函数(){
document.getElementById(“servicesShow”).className=“”;
document.getElementById(“servicesShow”).className=“servicesHideLink”;
});
$(“.servicesHideLink”)。单击(函数(){
document.getElementById(“servicesShow”).className=“”;
document.getElementById(“servicesShow”).className=“servicesShowLink”;
});
选择器计算一次并生成一组元素,然后事件处理程序绑定到这些元素,但不知道用于获取这些元素的选择器。因此,即使类更改,元素也不会更改,事件处理程序保持不变
您可以使用来获得您想要的:
$(document).on('click', ".servicesShowLink", function(){
$("#servicesShow").removeClass("servicesShow");
$("#servicesShow").addClass("servicesHideLink");
});
$(document).on('click', ".servicesHideLink", function(){
$("#servicesShow").removeClass("servicesHideLink");
$("#servicesShow").addClass("servicesShow");
});
我利用这个机会提出了更多jQuery风格的代码,而不是
文档。getElementById
调用。因此,即使类更改,元素也不会更改,事件处理程序保持不变
您可以使用来获得您想要的:
$(document).on('click', ".servicesShowLink", function(){
$("#servicesShow").removeClass("servicesShow");
$("#servicesShow").addClass("servicesHideLink");
});
$(document).on('click', ".servicesHideLink", function(){
$("#servicesShow").removeClass("servicesHideLink");
$("#servicesShow").addClass("servicesShow");
});
我利用这个机会建议使用更多jQuery风格的代码,而不是使用
document.getElementById
调用等doElement.classlist.toggle(“servicesHideLink”)代码>应该通过一个onclick事件解决您的问题。我怀疑问题在于,当您单击时,它会切换,并添加一个新的事件侦听器,该侦听器会启动。因此,使用一个事件侦听器是有意义的。使用doElement.classlist.toggle(“servicesHideLink”)代码>应该通过一个onclick事件解决您的问题。我怀疑问题在于,当您单击时,它会切换,并添加一个新的事件侦听器,该侦听器会启动。因此,使用一个事件侦听器是有意义的。无需先清除类名,只需将其设置为新值即可。将代码转换为显示行为的代码段。既然已经在使用jQuery,为什么还要使用document
?为什么不使用jQuery?我认为如果已经在使用jQuery,那么使用jQuery的toggleClass
将是最佳选择jQuery@RobG更改类还是添加类?如果将其从show改为hide,从hide改为show,我就不能这样做。不需要先清除类名,只需将其设置为新值即可。将代码转换为显示行为的代码段。既然已经在使用jQuery,为什么还要使用document
?为什么不使用jQuery?我认为如果已经在使用jQuery,那么使用jQuery的toggleClass
将是最佳选择jQuery@RobG更改类还是添加类?如果把它从“显示”改为“隐藏”,再从“隐藏”改为“显示”,我就做不到。