选项和jQuery .click()不能一起使用 [英] option & jQuery .click() won't work together
问题描述
这在FF中效果很好,但在IE,Chrome或Safari中效果不佳.
this works great in FF but not in IE, Chrome or Safari.
$('#countryDropDown option').click(function() {
var countryID = $(this).val();
dostuff();
});
// countryDropDown = id of select
因此,如您所见,我想将click事件附加到每个选项.
So, as you can see I want to attach a click event to each option.
我尝试过
var allOpts = $('#countryDropDown option'),
l = allOpts.length,
i = 0;
for (i = 0; i < l; i += 1) {
$(allOpts[i]).click(function() {
var countryID = $(this).val();
doStuff();
});
}
它仍然不希望在FF之外的任何其他浏览器中工作.我究竟做错了什么? 谢谢
It still does not want to work in any other browser but FF. What am I doing wrong? Thanks
推荐答案
问题是您是否真的需要这样做.我敢打赌,您不需要访问option
元素,因此您也可以使用 .change()
:
The question is if you really need to do it this way. I bet you don't need access to the option
element, so you also could use .change()
:
var countryID;
$('#countryDropDown').change(function() {
countryID = $(this).val();
dostuff();
});
更新:
根据文档,
According to the documentation, .val()
should work, but if it does not for whatever reason, do this:
var countryID;
$('#countryDropDown').change(function() {
countryID = $('option:selected', this).val();
dostuff();
});
Update2:
我不知道它是否相关(不过我认为它应该仍然有效),但是可能是您的option
元素没有value
属性,就像这样:
I don't know if it is relevant (I think it should work nevertheless) but could it be that your option
elements don't have a value
attribute, likes so:
<option>Foo</option>
如果是这样,您应该尝试使用.text()
而不是.val()
.
If so you should try .text()
instead of .val()
.
$('option:selected', this).text();
这篇关于选项和jQuery .click()不能一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!