I am trying to make a simple toggle button in javascript

后端 未结 5 1384
迷失自我
迷失自我 2020-12-19 04:28

I am trying to make a simple toggle button in javascript. However, the button will only turn \"OFF\" and will not turn back \"ON\"

&l         


        
5条回答
  •  不知归路
    2020-12-19 05:08

    Why are you passing the button if you're going to look it up?

    Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON.

    // Toggles the passed button from OFF to ON and vice-versa.
    function toggle(button) {
      if (button.value == "OFF") {
        button.value = "ON";
      } else {
        button.value = "OFF";
      }
    }
    

    If you wanna get fancy and save a couple of bytes you can use the ternary operator:

    function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";}
    

提交回复
热议问题