javascript - 更改 <option> 的 .html() 会将 <option> 的 selectedIndex 属性从 '-1' 重置为 '0'

标签 javascript jquery html dom

更改时使用 jQuery .html()<option><select> 里面(我之前将 selectedIndex 属性设置为 -1 )重置 selectedIndex <select>的属性(property)来自 '-1 ' 到 ' 0 '

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<select id="myselect" class="drpmnu">

   <option id="one" >(01)</option>

   <option id="two" >(02)</option>

   <option id="three" >(03)</option>

</select>
  <script>
    $(".drpmnu").prop('selectedIndex', -1)
    $('#three').html("moo")
  </script>
</body>
</html>

http://jsbin.com/filowe/2/edit?html,output

最佳答案

此案例在 HTML5 spec 中提到:

On setting, the selectedIndex attribute must set the selectedness of all the option elements in the list of options to false, and then the option element in the list of options whose index is the given new value, if any, must have its selectedness set to true and its dirtiness set to true.

Note: This can result in no element having a selectedness set to true even in the case of the select element having no multiple attribute and a display size of 1.

...

如果插入节点或删除节点导致选项列表获得或丢失一个或多个选项元素,或者选项列表中的选项元素 asks for a reset ,然后,如果选择元素的 multiple 属性不存在,选择元素的显示大小为 1,并且选择元素的选项列表中没有选项元素的selectedness设置为 true,用户代理必须设置树顺序选项列表中未禁用的第一个选项元素的选择度(如果有的话)为真。

通过设置其 innerHTML 来更改选项或 textContent属性触发此重置(Firefox 除外),但 text属性(仅 <option>)不会触发它(IE 除外)。

// these triggers the <select> element's reset (except on Firefox)
$("#three")[0].innerHTML   = "foo";
$("#three")[0].textContent = "foo";

// this does not trigger the reset (except on IE)
$("#three")[0].text = "foo";

Firefox 更严格地遵循规范,它只重置 <select>如果有新的<option> ,或者删除了一个 <option>秒。但它在设置 <option> 期间无法执行重置的 selected属性设置为 false(但 that should trigger 也会重置)。

简而言之,目前所有的浏览器都无法完全实现规范,因此唯一的跨平台解决方法是更改​​ selectedIndex作为选择(及其后代元素)的最后一个操作:

$("#three").html("moo");
$(".drpmnu").prop("selectedIndex", -1);

关于javascript - 更改 <option> 的 .html() 会将 <option> 的 selectedIndex 属性从 '-1' 重置为 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28209320/

相关文章:

javascript - 如何为进度条的宽度变化设置动画?

java - Java 中文件下载的文件夹浏览对话框

javascript - GetSubRaster 并在另一个 Canvas 中显示 PaperJS

html - 在我的 LI 中,为什么溢出的 bg 颜色与其余部分的 bg 颜色不同?

javascript - jQuery 多类 .hover 问题

javascript - Jquery .click 功能不起作用

javascript - XMLHttpRequest 无法在 angularjs 中加载

javascript - Microsoft JScript 运行时错误 : [$injector:modulerr] in AngularJS v1. 3.0-beta.11

javascript滚动到光标: rect.顶部更改

javascript - 当输入区域没有文本时,Jquery 提交按钮不会被禁用