【发布时间】:2012-06-21 03:33:13
【问题描述】:
我想让用户输入一个文本框并在选择下拉列表中查找并选择它。但是我有对象本身而不是它的名字。
目前在文本框上按回车将运行以下代码
$(this).prev().find('option:contains(\'editboxValue\')').attr('selected', 'selected');
但上面的代码只选择了Text2。以下代码工作正常,但看起来很乱!
$(this).prev().find("option").each(function(){ if ($(this).text() == 'editboxValue') $(this).attr("selected","selected");});
有没有更好的写法?
<select>
<option>Text</option>
<option>Text1</option>
<option>Text2</option>
</select>
<input type="text">
【问题讨论】:
-
你的
each循环永远不会选择一个元素。'+ $(this).val() +'是字面意思。你可以使用filter:api.jquery.com/filter -
@Felix:感谢您指出错误。我从附加到选择的部分事件中选择了这条线。我编辑了代码以显示我的意思