javascript 使用 Jquery 检测选择列表的变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5593534/
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
Detect change of select list using Jquery
提问by ?rjan
Is there a way to detect when the value of a select list is set to empty by a javasscript and notby the user? It seems that the change-event only triggers by mouse or keyboard.
有没有办法检测选择列表的值何时由 javascript 而不是由用户设置为空?似乎更改事件只能由鼠标或键盘触发。
And is there a way to detect when the number of options in a select list changes (added, removed)?
有没有办法检测选择列表中的选项数量何时发生变化(添加、删除)?
回答by istvan.halmen
You have to trigger the change event manually, when you are changing the value of a select with javascript. E.g:
当您使用 javascript 更改选择的值时,您必须手动触发更改事件。例如:
$('#myselect').val(10).change();
In this example the value is set to 10 and the change event is triggered. If there is an event handler attached to the select, it will be executed.
在此示例中,该值设置为 10 并触发更改事件。如果有一个附加到选择的事件处理程序,它将被执行。
回答by Bhanu Krishnan
回答by Rory McCrossan
To answer your first question, not it's not possible to detect what caused the change in the select list in the change event itself.
要回答您的第一个问题,不是不可能检测到是什么导致了更改事件本身中选择列表的更改。
However, if there is javascript code changing the select list you could add some logic in there to perform the tasks needed in this scenario.
但是,如果有 javascript 代码更改了选择列表,您可以在其中添加一些逻辑来执行此场景中所需的任务。