它突出显示了多个选项,因为
each
false
. 将代码大致修改为:
..
var notFound = true; // 1) initialize a shared variable
$('select#MMD > option').each(function() {
..
if(found a match) {
..
notFound = false; // 2) update it's value to force exit from loop
}
return notFound; // 3) keep iterating until notFound is true
});
..
或者,使用一个简单的for循环来保持逻辑清晰。
...
var options = $('#MMD > option');
for(var i = 0; i < options; i++) {
if found a match {
add "selected" attribute
return; // exists the `keypress` function immediately
}
}
..
而且,jQuery已经规范化了
event
对象,这样就不必检查
keyCode
或
which
.