Qt中如何通过按钮清空所有复选框和单选按钮?
实现点击按钮清空所有复选框和单选框的选中状态
原生JavaScript实现
直接通过DOM操作选中目标元素,绑定按钮点击事件后重置选中状态:
// 获取"clear all choices"按钮,若按钮有唯一id(比如id="clearAllBtn"),用getElementById更高效 const clearButton = document.querySelector('button'); clearButton.addEventListener('click', () => { // 清空所有复选框 document.querySelectorAll('input[type="checkbox"]').forEach(box => { box.checked = false; }); // 清空所有单选框 document.querySelectorAll('input[type="radio"]').forEach(radio => { radio.checked = false; }); });
如果页面存在多个按钮,务必给目标按钮设置唯一标识(如id),避免误绑定事件。
jQuery实现(项目已引入jQuery时使用)
用jQuery可以更简洁地完成批量操作:
// 绑定按钮点击事件 $('button:contains("clear all choices")').on('click', function() { // 同时清空复选框和单选框的选中状态 $('input[type="checkbox"], input[type="radio"]').prop('checked', false); });
可选优化
如果不需要清空禁用状态的输入框,可修改选择器排除禁用元素:
- 原生JS:
document.querySelectorAll('input[type="checkbox"]:not(:disabled)') - jQuery:
$('input[type="checkbox"]:not(:disabled), input[type="radio"]:not(:disabled)')
内容的提问来源于stack exchange,提问作者berkeozen
相关产品推荐
相关产品推荐

