javascript 选择 onblur/onchange 的替代方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15940354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternative to onblur/onchange in select
提问by Brian McCutchon
I am trying to find a way to run a JavaScript function when a user selects an option in an HTML select
box, regardless of whether this option was already selected. So onchange
is out of the question.
我试图找到一种在用户选择 HTMLselect
框中的选项时运行 JavaScript 函数的方法,而不管该选项是否已被选中。所以onchange
是不可能的。
The problem with using onblur
is that (in Chrome and Safari, at least) the event is not triggered until the user clicks another element. This can also prove annoying if the user focuses on the select, then clicks away without choosing an option, in which case I do not want the event to be triggered.
使用的问题onblur
是(至少在 Chrome 和 Safari 中)直到用户单击另一个元素时才会触发事件。如果用户专注于选择,然后在没有选择选项的情况下点击离开,这也会很烦人,在这种情况下,我不希望触发事件。
I was able to get some success by giving each of the options an onmouseup
handler, but this only works in Firefox, as far as I can tell. Any ideas?
通过为每个选项提供一个onmouseup
处理程序,我能够取得一些成功,但据我所知,这只适用于 Firefox。有任何想法吗?
采纳答案by Brian McCutchon
Since nobody has bothered to answer this, I'll post a generic version of my code:
由于没有人愿意回答这个问题,我将发布我的代码的通用版本:
<select id="mySelect" onfocus="this.selectedIndex=0;" onchange="userDidSomething(event)">
<option>Choose one:</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
The JavaScript:
JavaScript:
function userDidSomething(event) {
// Your Code Here.
}
回答by jonlastthelast
Try using
尝试使用
var s = document.getElementById("mySelect");
s.attachEvent("onchange", function() {
// function here
});