【问题标题】:Programmatically changing html select element not triggers events以编程方式更改 html 选择元素不会触发事件
【发布时间】:2021-06-30 11:02:57
【问题描述】:

Yahoo weather website 上有一个选择元素,可以通过以下方式检索:

let sel = document.querySelector('select');

您可以手动选择不同的选项(温度、风和降水)并查看每个选项的下一个 24 小时预报。问题是,当您以编程方式更改选项时(如下所示),尽管所选选项发生更改,但不会触发 onChange 事件(即预测不更新):

sel.selectedIndex = 1;

sel.selectedIndex = 2;

我已经测试了在类似线程上准备的不同解决方案(如this onethis one),但不幸的是它们都不起作用。任何帮助都将提前表示感谢。

【问题讨论】:

  • change()事件不会自动触发,需要自己触发,如sel.change();设置selectedIndex后触发
  • 调用sel.change()sel.onchange() 都会返回此错误:Uncaught TypeError: sel.onchange is not a function

标签: javascript html


【解决方案1】:

您需要使用以下代码:-

const sel = document.querySelector('select');
sel.value = 'precipitation'; // You can change this value to whatever you want
sel.dispatchEvent(new Event('change', {'view': window,'bubbles': true}));

【讨论】:

  • 听起来很棒!谢谢@Diwakar Singh。这对我有用。请您再解释一下最后一行吗?
  • 过去 15 分钟我一直在尝试这个,我只是错过了 bubbles: true 设置,我的错。我猜view: window 不是必需的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 2010-11-15
  • 1970-01-01
  • 2016-04-11
相关资源
最近更新 更多