`
zyongsheng83
  • 浏览: 41294 次
  • 性别: Icon_minigender_1
  • 来自: 大连
最近访客 更多访客>>
社区版块
存档分类
最新评论

向select里添加项并设置选中时的问题

 
阅读更多

假设有:
<select name="sname">
  <option value="1">class 1</option>
  <option value="2" selected>class 2</option>
</select>

执行:
var opt = document.createElement("option");
opt.value="3";
opt.innerHTML="class 3";
document.getElementById("sname").appendChild(opt);
document.getElementById("sname").selectedIndex=2;
//这样并不能选中第三项,只有新加的项会出现这种情况

解决:
在document.sname.selectedIndex=2;之前调用一下document.getElementById("sname").focus();
或者setTimeout(0, new Function("document.getElementById('sname').selectedIndex=2;")); 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics