当选择HTML选择/下拉列表中的项目时,什么事件触发? [英] What event fires when item in HTML select/dropdown list is selected?
问题描述
我想回应用户选择select元素中的项目。然而,这jQuery:
I want to respond to the user selecting an item in a select element. Yet this jQuery:
$('#platypusDropDown').select(function () {
alert('You selected something');
});
...什么也不做。虽然jsFiddle认为它是有效的jQuery,但它没有显示提示。
...does nothing. It shows no alert, although jsFiddle sees it as valid jQuery.
Click事件有效,但速度太快 - 在点击select元素之前触发,选择。
The Click event works, but it's too fast - it fires on clicking the select element, prior to making a selection.
当然,我真的很想做这样的事情:
Of course, I really want to do something like:
$('#platypusDropDown').select(function () {
var selection = $('platypusDropDown').val;
$.getJSON('platypus.json', selection, data() {
// . . .
});
});
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>
推荐答案
您需要使用 变更 事件
You need to use change event
$('#platypusDropDown').change(function () {
var selection = this.value; //grab the value selected
$.getJSON('platypus.json', selection, data() {
. . .
});
});
Fiddle
加上 $('platypusDropDown')。val
这里val应该是 val()
,你不需要再次创建一个jquery对象,该处理程序中的 this
表示DOM元素选择事件绑定到的),你可以直接使用 this.value
或 $(this).val() code>
Plus $('platypusDropDown').val
here val should be val()
and you dont need to create a jquery object again over the element, this
inside the handler represents DOM element (select on which the event is bound to) and you can directly access the value with this.value
or $(this).val()
这篇关于当选择HTML选择/下拉列表中的项目时,什么事件触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!