无需jQuery如何将attr('selected', true)相关代码转为原生JavaScript
原生JavaScript替代jQuery实现方案
错误原因说明
- 链式调用不合法:
setAttribute()方法没有返回值,你在该方法后直接链式调用dispatchEvent,相当于在undefined上调用方法,直接抛出类型错误。 - 属性操作方式错误:
selected是DOM元素的内置布尔属性(property),不是HTML标签的静态属性(attribute),用setAttribute修改通常不会生效;你尝试的selected() = true写法也不对,selected是属性不是方法,不需要加括号。 - 事件触发对象错误:
change事件是绑定在<select>元素上的,你给<option>触发事件不会触发select上绑定的监听回调。
正确实现代码
// 先获取目标option,增加存在性判断避免空指针报错 const targetOption = document.querySelector('#H10 option[value*="2"]'); if (targetOption) { // 直接设置选中状态 targetOption.selected = true; // 找到外层select元素触发change事件,配置bubbles保证事件正常冒泡 targetOption.closest('select').dispatchEvent(new Event('change', { bubbles: true })); }
内容的提问来源于stack exchange,提问作者HN117
相关产品推荐
相关产品推荐

