我最终创建了一种方法,该方法将使我的所有<select>
控件都以相同的方式运行,这样我就不必在每种特定情况下都执行一次性的 Javascript。这有点 hacky,但至少我避免了这样的重复代码:
$(function() {
// Make select lists in Chrome and IE behave more like Firefox: when they are focused
// but not open and the user starts typing, we don't want the "change" event to fire
// until the user has actually selected the value they want.
var invokePendingChanges = function () {
/// <summary>
/// Event handler which checks "this" select box for a code that shows that changed
/// events have been ignored. If it finds the code, it will invoke the 'change'
/// event on the input.
/// </summary>
var t = $(this);
if (t.data('change-pending')) {
setTimeout(function () {
t.data('change-pending', false);
t.change();
}, 0);
}
};
$('select')
.keydown(function(e) {
// If the user hit the enter key, invoke pending changes.
if (e.which == 13) {
invokePendingChanges.call(this);
} else {
var t = $(this);
// Be aware that date('events') isn't part of the official API, so it is subject
// to change with future versions of jQuery.
var allHandlers = t.data('events');
var changeHandlers = allHandlers ? allHandlers['change'] : null;
delete allHandlers['change'];
t.change(function() {
t.data('change-pending', true);
return false;
});
var revert = function() {
allHandlers['change'] = changeHandlers;
clearTimeout(timeout);
t.off('blur', revert);
};
t.on('blur', revert);
var timeout = setTimeout(revert, 0);
}
})
.blur(invokePendingChanges);
});