为每个收藏按键添加事件时,为什么“已收藏“总不能变回”收藏“?

//为每个收藏添加一个事件
var colength=$(".col").length;
for(var i=0;i<colength;i++){
    $(".col").eq(i).click(function(){
      alert($(this).text().length);//这地方提示是正常的,
//但当出现3时,并没有执行第一个if,这是为什么呢?

    if($(this).text().length==3){
       $(this).css("background","white");
       $(this).text("收藏");
        }
    if($(this).text().length==2){
           $(this).css("background","yellow");
       $(this).text("已收藏");
       }
       
})
}
阅读 2.4k
1 个回答

代码贯通了哦

if($(this).text().length==3){
   $(this).css("background","white");
   $(this).text("收藏");
}
//长度编程2
if($(this).text().length==2){
       $(this).css("background","yellow");
   $(this).text("已收藏");
}

==修改下===

if($(this).text().length==3){
   $(this).css("background","white");
   $(this).text("收藏");
}else if($(this).text().length==2){
       $(this).css("background","yellow");
   $(this).text("已收藏");
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题