这个问题困惑很久了,是在jQuery中addClass方法的问题?

//Css样式
<style>
.first{
padding:10px 0px 0px 20px;;
width:300px;
height:50px;
background-color:#339999;
}
span{
width:14px;
height:14px;
float:left;
}
.jia{
background-image:url(+.jpg);
}
.jian{
background-image:url(-.jpg);
}
</style>
//jQuery代码
<script src="JQ.js" type="text/javascript"></script>
<script>
$(
function(){
$(".first").toggle(
function(){
$(".first>span").addClass("jian");
},
function(){
$(".first>span").addClass("jia");
}
);
}
);
</script>
</head>

<body>
<div class="first">
<span class="jia"></span>
</div>
</body>
</html>
初始化:

第一次点击效果图:

再次点击还是

这是为什么,说下原因,为什么会这样,谢谢各位大侠了

精慕HU
浏览 258回答 1
1回答

幕布斯7119047

不要用addClass,因为用addClass之后,会让对象的class="jia jian",这样图片肯定是不会变的。你应该改成attr,比如上面两句:$(".first>span").addClass("jian"); 改成 $(".first>span").attr("class", "jian");$(".first>span").addClass("jia"); 改成 $(".first>span").attr("class", "jia");这样class就会在class="jia"和class="jian"之间互相切换了。
打开App,查看更多内容
随时随地看视频慕课网APP