如何在点击单选框选项后执行JavaScript函数?
原生JavaScript实现单选框点击显示文本框
完整代码实现
HTML
<!-- 单选框组 --> <input type="radio" id="yes" name="option"> <label for="yes">Yes</label><br><br> <input type="radio" id="no" name="option" checked> <label for="no">No</label><br><br> <!-- 需要显示/隐藏的区域 --> <div id="diet-section" style="display: none;"> <label for="edietq">If yes, explain your dietary restrictions</label><br> <input type="text" id="edietq" name="edietq"><br><br> </div>
JavaScript
function handleOptionChange() { const dietSection = document.getElementById('diet-section'); // 判断Yes单选框是否被选中 if (document.getElementById('yes').checked) { dietSection.style.display = 'block'; } else { dietSection.style.display = 'none'; } } function init() { // 给所有同组单选框绑定change事件 const radioOptions = document.querySelectorAll('input[name="option"]'); radioOptions.forEach(radio => { radio.addEventListener('change', handleOptionChange); }); } window.onload = init;
关键说明
- 监听
change事件而非click:点击单选框或其关联的label都会触发radio的change事件,覆盖所有交互场景,比单独监听click更可靠 - 初始隐藏目标区域:通过
style="display: none;"让饮食说明区域默认隐藏,避免页面加载时的视觉闪烁 - 批量绑定事件:通过
querySelectorAll选中所有同组单选框,一次性绑定事件,同时处理Yes和No的切换逻辑 - 用
checked属性判断状态:直接通过radio元素的checked属性判断是否被选中,逻辑清晰直观
内容的提问来源于stack exchange,提问作者Esther Lee
相关产品推荐
相关产品推荐

