使用jQuery设置下拉列表的选定索引 [英] Use jQuery to set selected index of a dropdown
问题描述
我在 SO
上也看到过关于同一主题的其他帖子,但是我还没有找到使用 jQuery
设置选择的解决方案.
I have seen other posts here at SO
about this very same subject, but I have not found a solution that is setting the select using jQuery
.
我有一个下拉菜单,如下所示:
I have a dropdown that looks like this:
<select type="select" id="docsList" name="docsList">
<option id="defaultListItem" value="0">Select a Document...</option>
<option value="38">Document 1</option>
<option value="35">Document 2</option>
<option value="46">Document 3</option>
<option value="45">Document 4</option>
</select>
我需要在 $.ajax()
成功函数中重置下拉菜单.我使用了以下内容:
I need to reset the dropdown within an $.ajax()
success function. I've used the following:
$('select#docsList option:selected').val('0');
$('select#docsList').attr('selectedIndex', 0);
...还有一些.
我开始认为这段代码很好,并且在防止重置下拉列表方面还有其他事情要做.
I'm beginning to think this code is fine and I've got something else going on preventing resetting the dropdown.
推荐答案
您正在使事情复杂化.您不需要jQuery来获取/设置< select>
的 selectedIndex
.
You're overcomplicating things. You don't need jQuery to get/set a <select>
's selectedIndex
.
$('#docsList').get(0).selectedIndex = 0;
设置< select>
的值时,请在< select>
而不是一个上调用 .val()
< option>
s
When setting the value of a <select>
, call .val()
on the <select>
, not on one of its <option>
s.
$('#docsList').val('0');
这篇关于使用jQuery设置下拉列表的选定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!