为什么动态地向select元素添加选项会改变其selectedIndex?

时间:2015-10-27 20:06:22

标签: javascript html

简单明了:为什么在select元素中添加选项会改变其selectedIndex,有没有办法:

  1. 防止此行为
  2. 检测
  3. var list = document.getElementById("list");
    list.selectedIndex = -1;
    document.write("</br>Selected index: " + list.selectedIndex);
    $(list).append('<option value="foo">foo</option>');
    document.write("</br>Selected index: " + list.selectedIndex);
    list.selectedIndex = -1;
    document.write("</br>Selected index: " + list.selectedIndex);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="list">      
    </select>

2 个答案:

答案 0 :(得分:0)

  

<强>的selectedIndex

     

By assigning -1 to this property, all items will be deselected. Returns -1 if no items are selected.

对于正常select,只有在没有要选择的项目时才能选择任何项目。只要添加至少一个项目,选择就必须

但是,如果您有select multiple,则会保留该值。

&#13;
&#13;
var list = document.getElementById("list");

document.write("</br>Selected index: " + list.selectedIndex);
$(list).append('<option value="foo">foo</option>');
$(list).append('<option value="foo">foo</option>');
$(list).append('<option value="foo">foo</option>');
document.write("</br>Selected index: " + list.selectedIndex);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="list" multiple>      
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在添加选项后手动重置它,基本上在list.selectedIndex = -1;之后添加$(list).append('<option value="foo">foo</option>');