IE vs. FireFox 系列 - getElementsByName問題

IE vs. FireFox 系列 - getElementsByName問題

因為要在前台做切換頁籤的功能,
所以為了方便所以打算將所有的div都用同樣的name,
然後先在getElementsByName取得所有的div後隱藏,
然後在顯示特定的div.
所以寫了如下的程式

Javascript - Copy Code

1 < SCRIPT LANGUAGE = " JavaScript " > 2 <!-- 3 function ShowSpan(objName) 4 { 5 var objarr = document.getElementsByName( " spn " ); 6 for ( var i = 0 ;i < objarr.length ;i ++ ) 7 { 8 objarr[i].style.display = " none " ; 9 } 10 var obj = document.getElementById(objName); 11 obj.style.display = " block " ; 12 } 13 14 // --> 15 </ SCRIPT >
Html - Copy Code

1 < input type ="button" name ="Show1" value ="Show span 001" onclick ="ShowSpan('spn1');" > &nbsp; 2 < input type ="button" name ="Show1" value ="Show span 002" onclick ="ShowSpan('spn2');" > &nbsp; 3 < input type ="button" name ="Show1" value ="Show span 003" onclick ="ShowSpan('spn3');" > &nbsp; 4 < input type ="button" name ="Show1" value ="Show span 004" onclick ="ShowSpan('spn4');" > &nbsp; 5 < input type ="button" name ="Show1" value ="Show span 005" onclick ="ShowSpan('spn5');" >< br > 6 < div id ="spn1" name ="spn" style ="display:" > span 001 </ div > 7 < div id ="spn2" name ="spn" style ="display:none;" > span 002 </ div > 8 < div id ="spn3" name ="spn" style ="display:none;" > span 003 </ div > 9 < div id ="spn4" name ="spn" style ="display:none;" > span 004 </ div > 10 < div id ="spn5" name ="spn" style ="display:none;" > span 005 </ div >

在firefox上,一切如預期的,
但是後來在ie上測才發現,
要隱藏的都藏不起來...

在網路上找了一下才發現,
原來在ie下,getElementsByName只對表單的物件有作用.

最後在這邊找到有人寫了個iefix的函數.
主要是先用tag去找物件,然後再判斷name是不是一樣.
一樣的話就塞到陣列中再回傳.

Javascript getElementsByName_iefix - Copy Code

1 function getElementsByName_iefix(tag, name) { 2 3 var elem = document.getElementsByTagName(tag); 4 var arr = new Array(); 5 for (i = 0 ,iarr = 0 ; i < elem.length; i ++ ) { 6 att = elem[i].getAttribute( " name " ); 7 if (att == name) { 8 arr[iarr] = elem[i]; 9 iarr ++ ; 10 } 11 } 12 return arr; 13 }


(snippet from http://www.dreamincode.net/code/snippet293.htm )

程式範例:
firefox正常,ie無法運作版

firefox跟ie皆正常版(fix版)