使用jQuery实现选中单选按钮修改其文本并重置另外两个文本的问题
问题根因
- 选中状态判断逻辑错误:
jQuery('#radio11').prop("checked", true)是赋值操作,会强制将radio11设为选中状态,而非判断该单选框是否被选中。正确的判断写法应为jQuery('#radio11').prop("checked"),仅传入属性名即可获取当前选中状态。 - 事件绑定丢失:你通过
html()方法直接替换了整个<p>标签的内容,原有绑定了change事件的<input>元素会被完全移除,新插入的<input>没有绑定对应的事件监听,因此后续触发不了状态更新逻辑。 - 不需要替换为普通按钮:
name属性相同的单选框原生支持互斥选中逻辑,比手动实现的互斥逻辑稳定性更高。
修复方案
你可以通过统一绑定事件、仅修改文本节点不替换输入元素的方式实现需求,无需修改原有HTML结构,参考代码如下:
// 预先存储所有单选框的原始文本,避免硬编码 const radioOriginalText = { radio11: '29 x 1', radio12: '27 x 2', radio13: '25 x 3' } // 统一给所有同组单选框绑定change事件,无需单独写三份监听 jQuery('input[name="delivery_option"]').on('change', function () { // 遍历所有同组单选框更新文本 jQuery('input[name="delivery_option"]').each(function () { const curId = jQuery(this).attr('id') const isChecked = jQuery(this).prop('checked') const newText = radioOriginalText[curId] + (isChecked ? ' is ON' : ' is OFF') // 仅替换<p>标签内的文本节点,保留<input>元素不破坏原有事件绑定 jQuery(this).parent().contents().filter(function () { return this.nodeType === 3 }).replaceWith(newText) }) })
如果愿意微调HTML,给文本部分加个单独的<span>标签,代码会更易维护:
调整后的HTML
<p style="display:inline-block" id="radio11l"> <input id="radio11" type="radio" name="delivery_option" value="29 x 1" required /> <span class="radio-label">29 x 1</span> </p> <p style="display:inline-block" id="radio12l"> <input id="radio12" type="radio" name="delivery_option" value="27 x 2"/> <span class="radio-label">27 x 2</span> </p> <p style="display:inline-block" id="radio13l"> <input id="radio13" type="radio" name="delivery_option" value="25 x 3" /> <span class="radio-label">25 x 3</span> </p>
对应简化后的JS代码
const radioOriginalText = { radio11: '29 x 1', radio12: '27 x 2', radio13: '25 x 3' } jQuery('input[name="delivery_option"]').on('change', function () { jQuery('input[name="delivery_option"]').each(function () { const curId = jQuery(this).attr('id') const isChecked = jQuery(this).prop('checked') jQuery(this).next('.radio-label').text(radioOriginalText[curId] + (isChecked ? ' is ON' : ' is OFF')) }) })
内容的提问来源于stack exchange,提问作者Dravis800
相关产品推荐
相关产品推荐

