单击时不更改属性

时间:2013-09-19 19:39:54

标签: jquery attr

此更改 param 属性的代码无效。请告诉我为什么?

$("#button").on("click",function(){
   if($(this).attr("param") == "Off"){
      $(this).attr("param","Play");
   }
   if($(this).attr("param") == "Play"){
      $(this).attr("param","Off");
   }
});

Example on JsFiddle

3 个答案:

答案 0 :(得分:2)

您的代码会更改一次,然后将其更改回来。您应该使用else语句。尝试:

$("#button").on("click",function(){

if($(this).attr("param") == "Off"){
    $(this).attr("param","Play");
} else if($(this).attr("param") == "Play"){
    $(this).attr("param","Off");
}

});

答案 1 :(得分:0)

@nullability答案是正确的,但我更喜欢使用switch

$("#button").on("click",function(){
    switch($(this).attr("param")) {
        case "Off":
            $(this).attr("param","Play");
            break;
        case "Play":
            $(this).attr("param","Off");
            break;
    }
});

working demo

答案 2 :(得分:0)

虽然我迟到但作为完整指南你可以试试这个

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
$("#but").on("click",function(){

if($(this).attr("param") == "Off"){
$(this).attr("param","Play");
}else if($(this).attr("param") == "Play"){
$(this).attr("param","Off");
}

});
});
</script>
<input type="button" id="but" param="Off" value="go" />

问题是“if else”,如上面的可空性所述。你的代码第一次改变了它,但是在下一刻它又改变了它。