JavaScript 实现单选框可取消选择
要实现单选框可取消选择的功能,可以使用 JavaScript 来操作单选框的状态。可以遍历所有单选框,并给它们添加一个事件监听器,当点击单选框时切换其选中状态。
HTML 代码:
<input type='radio' name='option' id='option1'>
<label for='option1'>选项1</label>
<input type='radio' name='option' id='option2'>
<label for='option2'>选项2</label>
<input type='radio' name='option' id='option3'>
<label for='option3'>选项3</label>
JavaScript 代码:
var radios = document.querySelectorAll('input[type='radio']');
radios.forEach(function(radio) {
radio.addEventListener('click', function() {
if (this.checked) {
this.checked = false;
}
});
});
这段代码首先通过 querySelectorAll 方法选择所有 type 为 'radio' 的单选框,然后使用 forEach 方法给每个单选框添加一个事件监听器。当单选框被点击时,检查其是否已被选中,如果是,则取消其选中状态。
这样,用户就可以任意选择一个单选框,再次点击已选中的单选框可以取消选择。
原文地址: https://www.cveoy.top/t/topic/qzQE 著作权归作者所有。请勿转载和采集!