這周公司要出sp3了,忙着測試產品包,我負責測試js的產品包,必須保證每一個范例都可以運行,測試了一天發現了不少問題,其中一個就是使用select的范例在ie8時顯示出問題,ie7下直接顯示不了option,經過查資料將其兼容了,這里記錄一下。
方法1:
代碼如下:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); s.add(new Option("A")); } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Firefox、Chrome、IE9、IE8、IE7、Safari、Opera顯示正常。
方法2:
代碼如下:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); s.appendChild(new Option("B")); } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Firefox、Chrome、Safari、Opera顯示正常,IE9、IE8、IE7下不能顯示。
方法3:
代碼如下:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); s.add(new Option("A")); s.insertBefore(new Option("B"), s.options[1]); } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Firefox、Chrome、Safari、Opera顯示正常,IE9、IE8、IE7下不能顯示。
方法4:
將方法3的insertBefore第二個參數去掉,也就是說我們第一個option就想使用insertBefore時,看一下情況:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); s.insertBefore(new Option("D")); } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Chrome、Safari顯示正常,Firefox、IE9、IE8、IE7、Opera下不能顯示。
方法5:
代碼如下:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); s.options[0] = new Option("E"); } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Firefox、Chrome、IE9、IE8、IE7、Safari、Opera顯示正常。
方法6:
代碼如下:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); var op = document.createElement("option"); op.appendChild(document.createTextNode("F")); s.appendChild(op); } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Firefox、Chrome、IE9、IE8、IE7、Safari、Opera顯示正常。
方法7:
代碼如下:
<html> <head> <title></title> <script type="text/javascript"> function init() { var s = document.getElementById("s"); s.innerHTML = "<option>X</option><option>Y</option>"; } </script> </head> <body onload="init()"> <select id="s" style="width:100px;background:lightskyblue"></select> </body> </html>
測試結果:Firefox、Chrome、Safari、Opera顯示正常,IE9、IE8、IE7下不能顯示。