0

此更改参数属性的代码不起作用。请告诉我为什么?

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

JsFiddle 上的示例

4

3 回答 3

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");
}

});
于 2013-09-19T19:43:24.963 回答
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;
    }
});

工作演示

于 2013-09-19T19:46:19.537 回答
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”。您的代码是第一次更改它,但在下一刻它又将其更改回来。

于 2013-09-19T19:53:04.327 回答