未触发附加到Option节点的事件 [英] Event attached to Option node not being fired
问题描述
我有这个代码
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);
}
此代码可在FF> 2(没有FF 1或FF 2进行测试),Opera(预设),Chrome(Webkit)中工作,并且不适用于IE.
当我单击选择框中的选项时,没有任何反应.似乎没有任何事件可以简单地发起,什么也没有!
问题.我该如何解决?
目标:(根据该代码)使警报出现
顺便说一句:为什么会这样?
附加说明:开发人员工具指出没有错误.
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.
推荐答案
为什么会这样?
Why does that happen?
此问题的根本原因已经在SO上讨论了几次:
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.
较旧版本的IE根本不支持<option>
元素上的click
事件.相反,您必须收听<select>
的change
(或click)
事件:
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');
}
});
如果尚未准备好option
变量,则可以使用<select>
的值进行测试:
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();
}
});
此外,要避免使用try..catch
和Stupid IE doesn't know how to follow the spec
,您可以执行以下操作:
Also, to avoid the try..catch
and Stupid IE doesn't know how to follow the spec
, you can do just:
$(selectBox).append(option);
这篇关于未触发附加到Option节点的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!