我看到了非常奇怪的行为-在Firefox中,如果你有一个没有选择任何项目的选择下拉列表,那么onchange事件就会触发onblur-即使你只是将焦点更改为页面上的另一个元素。我的选择只是一个普通的选择:
<select id="mySelect">
<option value="Value0">Value 0</option>
<option value="Value1">Value 1</option>
<option value="Value2">Value 2</option>
</select>
我的js是:
$("#mySelect").change(function(){
alert('Change event fired');
});
$("#mySelect").attr('selectedIndex', '-1');
请参阅以下jsfiddle:http://jsfiddle.net/W8QR4/
如果我真的点击了一个新选项(而不是升级到jquery的新版本。我知道,我现在一直在使用它),有什么方法可以防止onchange启动吗?
更改事件在不应该发生时触发。我知道代码本身确实有效
复制步骤:
- 单击选择的小向下箭头
- 将鼠标悬停在值1或值2上,但不要选择它
- 在其他输入中单击两次,这样焦点就会从选择中移除并传递给其他元素
这仅在下拉列表中选择任何项目之前有效。一旦做出选择,这种情况就不会发生
以下是我提出的答案,请随意评论/改进:
$("#mySelect").attr('selectedIndex', '-1');
//Capture the initial selection of each dropdown
$('select').each(function() {
$(this).data('initialSelection', String($(this).attr('selectedIndex')));
});
//Add click event to all options. When clicked, change initial selection and unbind the click event
$('select option').click(function() {
$(this).parent().data('initialSelection', '').attr('selectedIndex', this.index).find('option').unbind('click');
});
//Onchange, check if initial selection is still -1. (If there is a click it will be reset to '')
//Otherwise, it was just a hover - reset selected index to -1
$('select').change(function(e){
if($(this).data('initialSelection') == '-1'){
$(this).attr('selectedIndex', '-1');
}
});