轉自:http://www.cnblogs.com/boolean/archive/2007/09/02/879071.html
之前寫了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>
總結:這也算一個有點奇妙的問題吧。