使用jQuery设置下拉列表的选定索引

| 我在ѭ0seen处看到过其他与此主题相同的帖子,但是我没有找到使用
jQuery
设置select的解决方案。 我有一个下拉列表,如下所示:
<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()
成功函数内重置下拉菜单。我使用了以下内容:
$(\'select#docsList option:selected\').val(\'0\');
$(\'select#docsList\').attr(\'selectedIndex\', 0);
...和其他一些。 我开始认为这段代码很好,并且在阻止重置下拉列表方面还有其他事情要做。     
已邀请:
        您太复杂了。您不需要jQuery来获取/设置
<select>
selectedIndex
$(\'#docsList\').get(0).selectedIndex = 0;
设置
<select>
的值时,请在
<select>
而不是其
<option>
之一上调用
.val()
$(\'#docsList\').val(\'0\');
    
        
$(\'#docsList option[value=0]\').attr(\'selected\', \'selected\');
这会将值属性设置为0的ѭ11设置为所选选项。     
        马特的答案有一个小缺陷:
$(\'#docsList\').val(\'0\');
如果不在兼容模式下,以上代码将无法在IE 9中运行。以下适用于我的跨浏览器:
document.getElementById(\'docsList\').selectedIndex = 0;
不过,感谢您指出了正确方向的指针。     
        您想要
$(\'select#docsList\').val(\'0\');
参见以下示例:http://jsfiddle.net/uE2YN/     
        
$(\".btn-reset\").click(function () {
    $(\'#docsList\').val(\'123er43f-12fr-7hgy-ju78-kju345uy65r3\');
    $(\'#docsList\').trigger(\'chosen:updated\');
});
    

要回复问题请先登录注册