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>
1 个解决方案
#1
10
You need to use change event
您需要使用更改事件
$('#platypusDropDown').change(function () {
var selection = this.value; //grab the value selected
$.getJSON('platypus.json', selection, data() {
. . .
});
});
小提琴
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()
加上$('platypusDropDown')。val这里val应该是val()而你不需要再次在元素上创建一个jquery对象,这个处理程序里面代表DOM元素(事件绑定的选择)你可以使用this.value或$(this).val()直接访问该值
#1
10
You need to use change event
您需要使用更改事件
$('#platypusDropDown').change(function () {
var selection = this.value; //grab the value selected
$.getJSON('platypus.json', selection, data() {
. . .
});
});
小提琴
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()
加上$('platypusDropDown')。val这里val应该是val()而你不需要再次在元素上创建一个jquery对象,这个处理程序里面代表DOM元素(事件绑定的选择)你可以使用this.value或$(this).val()直接访问该值