之前写了js checkbox.checked=true在document.body.appendChild(checkbox)前与后赋值,提到如果想改变元素的视觉效果(checkbox.checked=true会打钩),请在把元素添加到页面上再为其赋值,否则赋值无效。下拉框元素也有这样的问题,比如在设置其selectedIndex属性时,会看到当前被选中的Item,浏览器重新绘画了这个元素。在某些情况下会出现这样的情况:用insertBefore方法添加了多个选项后,设置其selectedIndex不能起到效果,用options.add则不会。他们到底有什么区别呢?
测试代码如下:
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< title > Untitled Page </ title >
</ head >
< body onload ="f()" >
< select id ="s" >
</ select >
</ body >
< script >
function f(){
for ( var i = 0 ; i < 10 ; i ++ ){
var option = document.createElement('option')
// s.insertBefore(option)
s.options.add(option)
option.innerText = 'hello' + i
option.value = i
}
s.selectedIndex = 4
}
</ script >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< title > Untitled Page </ title >
</ head >
< body onload ="f()" >
< select id ="s" >
</ select >
</ body >
< script >
function f(){
for ( var i = 0 ; i < 10 ; i ++ ){
var option = document.createElement('option')
// s.insertBefore(option)
s.options.add(option)
option.innerText = 'hello' + i
option.value = i
}
s.selectedIndex = 4
}
</ script >
</ html >
总结:这也算一个有点奇妙的问题吧。