是否有一个onSelect事件或HTML< select>的等价物? [英] Is there an onSelect event or equivalent for HTML <select>?
问题描述
我有一个输入表单,可以让我从多个选项中进行选择,并在用户更改选择时执行某些操作。例如,
< select onChange =javascript:doSomething();>
< option> A< / option>
< option> B< / option>
< option> C< / option>
< / select>
现在, doSomething()
当选择改变时。
我想触发 doSomething()
选择任何选项,可能是同样的。
我曾尝试使用onClick处理程序,但在用户启动之前触发选择过程。
那么,有没有办法在用户的每次选择中触发一个函数?
更新:
Darryl建议的答案似乎有效,但并不一致。有时,只要用户点击下拉菜单,甚至在用户完成选择过程之前,事件就会被触发!
解决方案以下是最简单的方法:
< select name =abonchange =if(this.selectedIndex)doSomething );>
< option value = - 1> - < / option>
< option value =1>选项1< / option>
< option value =2>选项2< / option>
< option value =3>选项3< / option>
< / select>
兼顾鼠标选择和键盘向上/向下键选择焦点。
I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,
<select onChange="javascript:doSomething();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Now, doSomething()
only gets triggered when the selection changes.
I want to trigger doSomething()
when the user selects any option, possibly the same one again.
I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.
So, is there a way to trigger a function on every select by the user?
Update:
The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!
Here is the simplest way:
<select name="ab" onchange="if (this.selectedIndex) doSomething();">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
Works both with mouse selection and keyboard Up/Down keys whes select is focused.
这篇关于是否有一个onSelect事件或HTML< select>的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!