昨天,在項目中碰到了option顯示異常的原因,截圖如下:
Firefox中用css控制之後效果
chrome和IE中css不奏效
代碼:
| 代碼如下 |
複製代碼 |
<div class="controls"> <select name="ksname" id="ksname"> <?php while (!!$rowDK = fetchAssoc($resultDK)) { ?> <optgroup label="<?php echo $rowDK['name']; ?>"> <?php $resultKS = queryDB("select table_dake.id,table_keshi.sid,table_keshi.name from table_dake,table_keshi where table_dake.name='{$rowDK['name']}' and table_keshi.sid=table_dake.id"); while(!!$rowKS = fetchAssoc($resultKS)) { ?> <option value ="<?php echo $rowKS['name']; ?>"><?php echo $rowKS['name']; ?></option> <?php </optgroup> } } free($resultDK); free($resultKS); ?> </select> </div> |
調試了很久,在網上也找了方法,最終無果,只要去請教大牛了。大牛建議我去查看一下原始碼,是不是樣式改變了?這段代碼的select部分沒有任何樣式,怎麼會多?看了原始碼之後,樣式的確沒有多,但是每個option後面多了一個</optgroup>.又回頭看了代碼,才明白,我把</optgroup>寫在了內迴圈中,按照我的邏輯,本應該放在外迴圈。調整之後,一切正常。
補充一個:
select 是列表型元素中的一個很重要的代表。總結下他的一些書寫注意事項。
1.關於innerHTML ,在ie下不支援innerHTML的形式添加option選項,firefox,chrome是支援的。
2.添加option,使用 ele.options.add(option) ,但是這裡的option 可以是new Option(text,value)的形式構造的,也可以是通過
原生的函數document.createElement函數建立的。此外add的方式不會覆蓋以前的。option不能是html的形式。
3.選定特定的一個option的方式 ele.value = option.value;反之,如果當前是特定的option的話,
那麼ele的值一定就是option.value;
4.獲得選定的option的值還有另一個方式(我不太推薦)ele.options[ele.selectedIndex].value,這個儘管複雜一點,但是說明一個問題,
即列表型元素的清單項目有一個索引的概念。
| 代碼如下 |
複製代碼 |
<!DOCTYPE HTML> <html > <head> <meta http-equiv="Content-Type" content="text/html;charset=gb2312" /> <title></title> </head> <body> <select name="test" id="test"> <option value="etcyby">hehe</option> </select> <script type="text/javascript"> function $(id){ return document.getElementById(id); } function render(){ for(var i = 0 ;i < 100;i++){ var ele = document.createElement('option'); ele.text ='etcyby' + i; ele.value = i; $('test').options.add(ele); } $('test').value = '99' //alert($('test').options[$('test').selectedIndex].value); } function render2(){ $('test').innerHTML = '<option value="etcyby">hehe</option>'; } render(); </script> </body> |