如何以编程方式更改选择以激活其onchange行为?

如何以编程方式更改选择以激活其onchange行为?

问题描述:

这似乎不起作用:

<select id="mySel" onchange="alert('foo')">
    <option value="a">a</option>
    <option value="b">b</option>
</select>

<script>
dojo.byId('mySel').value = 'b'; // select changes, but nothing is alerted
</script>

(我正在使用dojo,但这并不重要。)

(I'm using dojo, but that doesn't really matter.)

onchange名称有点误导,除非您了解更改事件并且更改的值不是'同样的事情。当用户更改浏览器中的值时,会发生更改事件。我相信您可以通过在以编程方式更改值之后调用 dojo.byId('mySel')。onchange()来手动触发事件。 (你可能需要实际定义一个调用 alert 的函数。我自己没有这样做。)

The 'onchange' name is a little misleading unless you understand that a change event and a value being changed aren't the same thing. A change event occurs when the user changes the value in the browser. I believe you can fire the event manually by calling dojo.byId('mySel').onchange() after you programmatically change the value, though. (You might need to actually define a function that calls alert, though. I haven't done this myself.)