问题
I have this code
var option = new Option(thatOption.text, thatOption.value);
$(option).click( function(){
//Sorry cannot reveal what is here I'll just use this so that it can be referenced
alert("clicked");
}
);
try{
selectBox.add(option,null);
}catch(e){
// Stupid IE doesn't know how to follow the spec
selectBox.add(option);
}
This code works in FF > 2 (don't have FF 1 oe FF 2 to test), Opera (presto), Chrome (webkit) and doesn't work on IE.
When I click the option in the selectbox nothing happens. No event seems to be launched simply, nothing!
Question. How can I solve that?
Objective: (according to that code) make the alert appear
BTW: Why does that happen?
Extra note: The developer tools state that there are no errors involved.
回答1:
Why does that happen?
The root cause of this has been discussed a few times already on SO:
- option & jQuery .click() won't work together
- click event for option doesn't work in IE
- Click on option event
- etc.
Older versions of IE simply don't support click
events on <option>
elements. Instead, you'll have to listen to the <select>
's change
(or click)
event:
$(selectBox).change(function () {
});
Regarding your specific task, to have the alert
appear (or your actual code execute) only when that option is selected, you can test if the option
is selected within the change
event:
var option = new Option(thatOption.text, thatOption.value);
$(selectBox).change(function () {
if ($(option).is(':selected')) {
alert('clicked');
}
});
If you don't have the option
variable at the ready, you can instead test with the value of the <select>
:
$(selectBox).change(function () {
if ($(this).val() === 'something') {
alert();
}
});
Also, to avoid the try..catch
and Stupid IE doesn't know how to follow the spec
, you can do just:
$(selectBox).append(option);
来源:https://stackoverflow.com/questions/7760177/event-attached-to-option-node-not-being-fired