我看到非常奇怪的行为 - 在 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/
如果我有什么方法可以防止 onchange 触发havent实际上单击了一个新选项(除了升级到较新版本的 jquery 之外。我知道,我现在坚持使用它)?
更改事件在不应该的时候触发。我知道代码本身确实有效。
复制步骤:
- 单击选择的小向下箭头
- 将鼠标悬停在值 1 或值 2 上,但是不要选择它
- 单击other输入 - 两次,因此焦点从选择中移除并传递到另一个元素
这只适用于在下拉列表中选择任何项目之前。一旦做出选择,这种情况就不会发生
这是我想出的答案,欢迎评论/改进:
$("#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');
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)