今天在<ASP:radiobuttonlist/>中使用教本的的時候才注意到原來 document.getElementsByName 、document.getElementById 在IE與FF中有著不同實現。
對於ID & Name 按最經典的解釋的:“ID 就如同我們的SFZ,Name就如同我們的名字”,也就是說,在一個Html文檔中ID是唯一的,但是Name是可以重復的,就象我們的人名可以重復但是SFZ確實全中國唯一的(PS:據說有重復的^_^)
但是對於document.getElementsByName 與document.getElementById 這個兩個方法,IE中是並沒有嚴格區分 ID 與 Name 的,比如:
<script type="text/Javascript">
function useGetElementsByNameWithId(id)
{
var eles = document.getElementsByName('ID_A');
var msg = '使用 getElementsByName 傳入 ID:得到:'
if(eles.length > 0)
{
msg += " Name " + eles[0].id;
}
alert(msg);
}
function usegetElementByIdWithName(name)
{
var ele = document.getElementById(name);
var msg = '使用 getElementById 傳入 Name 得到:';
if(ele)
{
msg += " ID " + ele.id;
alert(msg);
}
</script>
<input id="ID_A" name="Name_A" type="button" value="使用 getElementsByName 傳入 ID" onclick="useGetElementsByNameWithId(this.id)" />
<input id="ID_B" name="Name_B" type="button" value="使用 getElementsByName 傳入 Name" onclick="usegetElementByIdWithName(this.name)" />IE中通過 getId 傳入 name 同樣可以訪問到目標元素,而通過 getName 傳入 Id 也可以訪問到目標元素。
getElementById Method
--------------------------------------------------------------------------------
Returns a reference to the first object with the specifIEd value of the ID attribute.
Remarks
When you use the getElementsByName method, all elements in the document that have the specifIEd NAME or ID attribute value are returned.
Elements that support both the NAME and the ID attribute are included in the collection returned by the getElementsByName method, but not elements with a NAME expando.
<ASP:radiobuttonlist id="RadioButtonList1" runat="server">
<asp:listitem>opt1</ASP:listitem>
<asp:listitem>opt2</ASP:listitem>
<asp:listitem>opt3</ASP:listitem>
</ASP:radiobuttonlist>Html:
<table id="RadioButtonList1" border="0">
<tr>
<td><input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="opt1" /><label for="RadioButtonList1_0">opt1</label></td>
</tr><tr>
<td><input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="opt2" /><label for="RadioButtonList1_1">opt2</label></td>
</tr><tr>
<td><input id="RadioButtonList1_2" type="radio" name="RadioButtonList1" value="opt3" /><label for="RadioButtonList1_2">opt3</label></td>
</tr>
</table>