我有以下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,请原谅详细说明。
答案 0 :(得分:1)
它突出显示多个选项,因为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
。