简体   繁体   English

多个切换按钮由单个功能控制

[英]Multiple toggle buttons controlled by single function

Still learning the ropes of JS and attempting to create a function that will toggle a button on and off, this works just fine. 仍在学习JS的精髓,并尝试创建一个可以打开和关闭按钮的函数,效果很好。 using the following. 使用以下内容。 (Please ignore the handlebars.js) (请忽略handlebars.js)

What I'm wondring is how do I create a single function to handle 6 seperate toggles. 我要做的是如何创建一个函数来处理6个单独的切换。

Cheers in advance, 提前加油

a newbie. 一个新手。

 function toggle(button) { if(document.getElementById("1").value=="OFF"){ document.getElementById("1").value="ON";} else if(document.getElementById("1").value=="ON"){ document.getElementById("1").value="OFF";} } 
  <input type="button" id="1" {{#if profile.userSettings.notificationSettings.enabled}} value="ON" {{else}} value="OFF" {{/if}} onclick="toggle(this); "> 

First of all, don't start an ID with a numeric. 首先,不要以数字开头的ID。

For you main issue, you can simply use the parameter button of your function and check its value. 对于主要问题,您只需使用函数的参数button并检查其值即可。

 function toggle(button){ button.value = button.value == 'OFF' ? 'ON' : 'OFF'; } 
 <input type="button" value="ON" onclick="toggle(this);"> <input type="button" value="OFF" onclick="toggle(this);"> <input type="button" value="ON" onclick="toggle(this);"> 

PS : PS:

button.value = button.value == 'OFF' ? 'ON' : 'OFF'

Is the ternary operator equivalent of 三元运算符等于

if(button.value == 'OFF'){
    button.value = 'ON';
}else{
    button.value = 'OFF';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM