javascript 已选择选项的 HTML 选择元素 onchange 触发器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3354367/
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
HTML select element onchange trigger for already selected option
提问by Shrey
I have the following HTML containing a drop down list (single selection)
我有以下 HTML 包含下拉列表(单选)
<script type="text/javascript">
$(document).ready(function () {
$("#garden").bind('change', function() {
alert("Changed");
});
});
</script>
<body>
<div id="content">
<select id="garden">
<option value="flowers">Flowers</option>
<option value="shrubs">Shrubs</option>
<option value="trees">Trees</option>
<option value="bushes">Bushes</option>
</select>
</div>
</body>
</html>
When the HTML page is rendered, Flowersis the already selected element in the drop-down by default (being the first one). If I select any other value (other than "Flowers"), the javascript function is fired and a alert box containing "Changed" is shown.
呈现 HTML 页面Flowers时,默认情况下是下拉列表中已选择的元素(第一个)。如果我选择任何其他值(“Flowers”除外),则会触发 javascript 函数并显示包含“已更改”的警报框。
Q1: But, in case I re-select Flowersagain, the onchangeevent is not triggered. I understand it is because nothing was 'changed' in the drop-down list. Is there a way a function is triggered even when no change to the already selected value in drop-down is done?
Q1:但是,如果我再次重新选择Flowers,onchange则不会触发该事件。我知道这是因为下拉列表中没有“更改”。即使没有更改下拉列表中已选择的值,是否也可以触发功能?
Q2: How to extract the value of the element which has just been selected (even if nothing new was selected - that is, user clicked on the drop down, and simply clicked somewhere else).
Q2:如何提取刚刚选择的元素的值(即使没有选择任何新元素——也就是说,用户点击下拉菜单,然后简单地点击其他地方)。
I have already tried the "onblur" but that requires that the user clicks somewhere else on the document so that the drop-down loses focus. Any help would be really appreciated.
我已经尝试过“onblur”,但这要求用户单击文档上的其他位置,以便下拉菜单失去焦点。任何帮助将非常感激。
Thanks a lot. [I have edited out the HTML headers and other script inclusions in the code snippet provided for brevity.]
非常感谢。 [为简洁起见,我在代码片段中编辑了 HTML 标头和其他脚本内容。]
采纳答案by jAndy
Well I think I don't get you 100%, but some things I can suggest here are:
好吧,我想我不能 100% 了解您,但我可以在这里建议一些事情:
bind a click event handler to the
select$("#garden").bind('click', function() { alert($(this).find('option:selected').text()); });bind a
focusoutevent handler$("#garden").bind('focusout', function() { alert($(this).find('option:selected').text()); });
将点击事件处理程序绑定到
select$("#garden").bind('click', function() { alert($(this).find('option:selected').text()); });绑定
focusout事件处理程序$("#garden").bind('focusout', function() { alert($(this).find('option:selected').text()); });
and of course bind the changeevent handler which you already got. The click event handlermight be a little bit tricky since it would fire every time you click on the element. But if you don't alert()it every time it should not be a problem at all, you got the current selection and can do with it whatever you want.
当然,绑定change你已经得到的事件处理程序。这click event handler可能有点棘手,因为每次单击元素时它都会触发。但是,如果您alert()每次都不这样做,那么它根本就不成问题,您将获得当前选择并可以随心所欲地使用它。
回答by Jon
You can manually trigger the event when you load the page:
您可以在加载页面时手动触发事件:
$(document).ready(function() {
$("#garden").bind("change", function() {
// ...
}).change();
});
This will pick up the initial value - so I think it makes your second question irrelevant. This won't work in all situations (I'm hoping that your actual handler isn't an alert but actually something useful!), but could come in handy...
这将获取初始值 - 所以我认为它使您的第二个问题无关紧要。这不适用于所有情况(我希望您的实际处理程序不是警报,而是有用的东西!),但可以派上用场......
回答by Chris
Are you sure that whatever you are doing is the most sensible way to do things? It seems like very strange UI to have different behaviour if you select an item by leaving it as the default compared to selecting it by opening up the select and selecting the currently selected item.
你确定无论你做什么都是最明智的做事方式吗?与通过打开选择并选择当前选定的项目来选择它相比,如果通过将项目保留为默认值来选择项目,则具有不同的行为似乎非常奇怪。
If you are wanting to make them explicitly choose flowers then maybe you want a dummy entry at the top that says "Please choose one" that will then mean they are forced to actually change to flowers if that is what they want. It would probably be simpler than complicating your code with more event handlers and such like.
如果您想让他们明确地选择鲜花,那么您可能希望在顶部有一个虚拟条目,上面写着“请选择一个”,这意味着如果他们想要的话,他们将被迫实际换成鲜花。这可能比使用更多事件处理程序等使代码复杂化更简单。
If you do really need to go down the path you are following then you may want to consider what the behaviour is if somebody just tabs to the control and then past it. ie should that fire your script off as well?
如果您确实需要沿着您所遵循的路径前进,那么您可能需要考虑如果有人只是点击控件然后通过它,行为是什么。即是否也应该关闭您的脚本?
Edit to respond to comment at length:
编辑以详细回应评论:
What you will want to do in this case is hook into the onSubmit handler of the form. This is called, as you can imagine, when the form submits. If your handler returns false that form will not be submitted.
在这种情况下,您要做的是挂钩到表单的 onSubmit 处理程序。正如您可以想象的那样,这在表单提交时被调用。如果您的处理程序返回 false,则不会提交该表单。
This handler is traditionally where you would do client side validation by examining the state of whatever form elements you care about and checking their values are valid. In this case you'd check if the value of garden was "N/A" or whatever you set it to and if so pop up an alert (in the simplest case) and possibly mark whichever fields need attention. Then the user will choose a valid entry (hopefully) and next time he submits your validation will succeed, you return true in the handler and the user can be happy he submitted valid input.
这个处理程序传统上是您通过检查您关心的任何表单元素的状态并检查它们的值是否有效来进行客户端验证的地方。在这种情况下,您将检查花园的值是否为“N/A”或您设置的任何值,如果是,则弹出警报(在最简单的情况下)并可能标记需要注意的字段。然后用户将选择一个有效的条目(希望如此),下次他提交您的验证将成功,您在处理程序中返回 true 并且用户可以很高兴他提交了有效的输入。
As always though the standard disclaimer that any data can be sent to your server by a determined user so you should not assume that just becasue you had this validation that you are getting valid data on the server. :)
与往常一样,尽管标准免责声明任何数据都可以由确定的用户发送到您的服务器,因此您不应该仅仅因为您进行了此验证就认为您正在服务器上获取有效数据。:)
回答by OuzoPower
To my opinion, the easiest solution is to duplicate the first option into a disabled and hidden element having the same label. Your dropdown list will display the label of the hidden option, but thus won't be displayed in the list.
在我看来,最简单的解决方案是将第一个选项复制到具有相同标签的禁用和隐藏元素中。您的下拉列表将显示隐藏选项的标签,但不会显示在列表中。
<select id="garden" name="blabla" onchange="this.form.submit();" >
<option value="" disabled selected style="display:none;">Flowers</option>
<option value="flowers" >Flowers</option>
<option value="shrubs" >Schrubs</option>
<option value="trees" >Trees</option>
<option value="bushes" >Bushes</option>
</select>
Your question seems same as HTML SELECT - Trigger JavaScript ONCHANGE event even when the option is not changedand the solution mentionned above was provided by Simon Aronsson.
您的问题似乎与HTML SELECT - Trigger JavaScript ONCHANGE event相同,即使选项未更改,并且上面提到的解决方案由 Simon Aronsson 提供。
Nota bene : the solution works perfectly with Firefox, but not with Internet Explorer.
注意:该解决方案适用于 Firefox,但不适用于 Internet Explorer。
回答by Jim W.
Question 1: I think the event for that would be "onSelect".
问题 1:我认为该事件是“onSelect”。
Question 2: I think the "onSelect" event would work for that as well, not 100% sure. Something to try at least and mess with.
问题 2:我认为“onSelect”事件也适用,但不是 100% 肯定。至少可以尝试并弄乱一些东西。

