option & jQuery .click() won't work together

耗尽温柔 提交于 2020-01-06 07:10:41

问题


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

So, as you can see I want to attach a click event to each option.

I alos tried

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();
    });
}

It still does not want to work in any other browser but FF. What am I doing wrong? Thanks


回答1:


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();
});

Update:

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:

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>

If so you should try .text() instead of .val().

$('option:selected', this).text();



回答2:


meow we have the same problem...

this is the solution:

if you want to access id of each option. this will do.

$("#countryDropdown").change(function() {
   var countryId = $('option:selected',this).attr('id');
   dostuff();
});



回答3:


val() is used to retrieve the value of a form element. An option is not a form element but a sub-element if you will. Further more your approach will not work if they use the keyboard. You are better off doing it this way.

$("#countryDropdown").change(function() {
    var countryId = $(this).val();
    dostuff();
});


来源:https://stackoverflow.com/questions/2817818/option-jquery-click-wont-work-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!