jQuery 选择 HTML 选择/下拉列表中的项目时会触发什么事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17414390/
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
What event fires when item in HTML select/dropdown list is selected?
提问by B. Clay Shannon
I want to respond to the user selecting an item in a select element. Yet this jQuery:
我想响应用户在 select 元素中选择一个项目。然而这个jQuery:
$('#platypusDropDown').select(function () {
alert('You selected something');
});
...does nothing. It shows no alert, although jsFiddle sees it as valid jQuery.
...什么也没做。它没有显示警报,尽管 jsFiddle 将其视为有效的 jQuery。
The Click event works, but it's too fast - it fires on clicking the select element, prior to making a selection.
Click 事件有效,但它太快了 - 在进行选择之前,它会在单击 select 元素时触发。
Of course, I really want to do something like:
当然,我真的很想做这样的事情:
$('#platypusDropDown').select(function () {
var selection = $('platypusDropDown').val;
$.getJSON('platypus.json', selection, data() {
// . . .
});
});
The HTML:
HTML:
<select id="platypusDropDown">
<option value="duckbill">duckbill</option>
<option value="duckbillPlatypus">duckbillPlatypus</option>
<option value="Platypus">Platypus</option>
<option value="Platypi">Platypi</option>
</select>
采纳答案by PSL
You need to use changeevent
您需要使用更改事件
$('#platypusDropDown').change(function () {
var selection = this.value; //grab the value selected
$.getJSON('platypus.json', selection, data() {
. . .
});
});
Plus $('platypusDropDown').valhere val should be val()and you dont need to create a jquery object again over the element, thisinside the handler represents DOM element (select on which the event is bound to) and you can directly access the value with this.valueor $(this).val()
加上$('platypusDropDown').val这里 val 应该是val(),你不需要在元素上再次创建一个 jquery 对象,this处理程序内部代表 DOM 元素(选择事件绑定到的元素),你可以直接访问该值this.value或$(this).val()

