Javascript 以编程方式更改html select元素不会触发事件

Javascript 以编程方式更改html select元素不会触发事件,javascript,html,Javascript,Html,在上,有一个select元素,可通过以下方式检索: let sel = document.querySelector('select'); 您可以手动选择不同的选项(温度、风和降水),并查看每个选项的下一个24小时预报。问题是,当您以编程方式更改选项(如下所示)时,尽管所选选项发生更改,但onChange事件不会触发(即预测不更新): sel.selectedIndex=2 我已经测试了在类似线程上准备的不同解决方案(如和),但不幸的是,它们中没有一个有效。我们将提前感谢您的帮助。您需要使用以

在上,有一个select元素,可通过以下方式检索:

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

sel.selectedIndex=2


我已经测试了在类似线程上准备的不同解决方案(如和),但不幸的是,它们中没有一个有效。我们将提前感谢您的帮助。

您需要使用以下代码:-

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}));


change()selectedIndex
后,调用
sel.change()
sel.onchange()
返回此错误:未捕获类型错误:sel.onchange不是函数。听起来很棒!谢谢你,迪瓦卡·辛格。这对我很管用。请你再解释一下最后一行好吗?我在过去15分钟里一直在尝试这个,我只是错过了
气泡:true
设置,我的错。我猜
view:window
不是必需的。
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}));