You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:27:01