简体   繁体   English

这是使用复选框的正确方法吗?

[英]Is this the proper way to use a checkbox?

Is this the proper way to use a checkbox in JS.这是在 JS 中使用复选框的正确方法吗? I can only get the event to fire one time, not each time I click the box.我只能让事件触发一次,而不是每次单击该框时。

 var checkbox = document.checkbox; checkbox.addEventListener('change', function(){ switch(this.value){ case "on": checkbox.value = "off"; break; case "off": checkbox.value = "on"; break; }
 <input type="checkbox" name = "checkbox" checked = "checked" value = "on">

You don't want spaces around your equals sign in HTML.在 HTML 中,您不希望等号周围有空格。 Also, a switch statement is a little verbose for when you have less than three conditions.此外,当条件少于三个时,switch 语句有点冗长。

Not sure what you are trying to accomplish exactly, but here you go.不确定你想要完成什么,但你去吧。

 var checkbox = document.querySelector('.checkbox'); checkbox.addEventListener('change', function(){ this.checked ? this.setAttribute('value', 'on') : this.setAttribute('value', 'off'); });
 <input class="checkbox" type="checkbox" name="checkbox" />

Make sure to get a reference to the checkbox using the proper API:确保使用正确的 API 获取对复选框的引用:

 // Get a reference to the element the proper way: var checkbox = document.querySelector("input[type='checkbox']"); checkbox.addEventListener('change', function(){ switch(this.value){ case "on": this.value = "off"; break; case "off": this.value = "on"; break; } console.log(this.value) });
 <input type="checkbox" name = "checkbox" checked = "checked" value = "on">

With that said, it's not super useful to change the value of a checkbox because it's checked.话虽如此,更改复选框的值并不是很有用,因为它已被选中。 The usual way a checkbox is used is either to submit its value as part of a form submission or to use as a Boolean indicator of some state for "in-page" behavior.使用复选框的通常方式是将其value作为form提交的一部分提交,或者用作“页内”行为的某种状态的布尔指标。 You generally don't want or need to change the value of a checkbox, instead you simply want to know if it is checked, which can be done by looking at its .checked property and making decisions based on that.您通常不想或不需要更改复选框的value ,而只想知道它是否被选中,这可以通过查看其.checked属性并基于此做出决定来完成。 A checkbox will have a checked property value of true when it's been checked and false when it isn't.复选框在被checked属性值为true ,未选中时为false

 // Get a reference to the element the proper way: var checkbox = document.querySelector("input[type='checkbox']"); checkbox.addEventListener('change', function(){ if(this.checked){ console.log("Checkbox is checked! Do something about it!"); } else { console.log("Forget it. Checkbox wasn't checked."); } });
 <input type="checkbox" name = "checkbox" value = "on">

No need of JS for this:不需要 JS:

 #chkBx + label { display:none; } #chkBx:checked + label { display:inline; } #chkBx:checked + label + label { display:none; }
 <input type="checkbox" id="chkBx" checked ><label for="chkBx">On</label><label for="chkBx">Off</label>

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

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