迭代选择列表以突出显示项目,依次突出显示每个项目
问题描述:
我有以下jQuery方法,它遍历包含多个选项的选择列表。我想让第一行匹配用户键入的文本到名为MMDCriteria的文本框中。目前,代码依次选择并突出显示每个项目,直到它到达列表的末尾。迭代选择列表以突出显示项目,依次突出显示每个项目
$("#MMDCriteria").bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
var criteria = $(this).val().toUpperCase();
alert("");
$('select#MMD > option').each(function() {
var optionValue = $(this).text().toUpperCase();
alert(optionValue.substring(0, optionValue.indexOf(criteria)));
if(optionValue.substring(0, optionValue.indexOf(criteria)) > -1) {
$(this).attr('selected', 'selected');
}
});
}
});
我刚刚开始使用jQuery,所以原谅冗长。
答
它突出显示了多个选项,因为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
。该物业将永远被命名为which
。