2011-02-03 78 views
0

一些簡單的代碼:IE,的getElementById和單選按鈕

<input type="radio" id="knob-reassign-leave" name="knob-reassign" value="n" checked="checked">Leave <br> 
<input type="radio" id="knob-reassign-cmp" name="knob-reassign" value="d"> Default <br> 
<input type="radio" id="knob-reassign" name="knob-reassign" value="r"> Reassign to 

<select name="assigned_to" id="assigned_to" onchange=" 
    if ((this.value != 'currentuser') && (this.value != '')) { 
    var kr = document.getElementById('knob-reassign'); 
    document.getElementById('knob-reassign').checked=true; 
    }"> 

    <option value="otheruser">Someone Else</option> 
    <option value="lastuser">Someone Third</option> 
    <option value="currentuser" selected="selected">Me</option> 
</select> 

這一切工作相當不錯,在FF和鉻,但我總是聽到時我寫的代碼,這並不在IE瀏覽器。看起來,IE正在爲該ID搜索「名稱」,或者它試圖將該ID轉換爲名稱,因爲它總是選擇第一個廣播,當它應該抓住最後一個時。

+0

我剛測試過,它爲我選擇了最後一個單選按鈕。 – Kaitnieks 2011-02-03 14:43:27

回答

0

當名稱和ID相同時,IE6/7/8確實似乎選擇了第一個<input>元素。下面是一個簡單的測試情況:

<input type="radio" id="a" name="c" value="1"> 
<input type="radio" id="b" name="c" value="2"> 
<input type="radio" id="c" name="c" value="3"> 

<script type="text/javascript"> 
    // Should get 3rd <input> with id 'c' and alert '3' 
    // Instead finds 1st input with name 'c' and alerts '1' 
    alert(document.getElementById('c').value); 
</script> 

雖然我不能提供解釋(Google has tons of relevant results),我可以提供一個修復:要麼override IE's implementation of getElementById或更改的最後一個元素的ID以從名稱是不同的:

<input type="radio" id="knob-reassign-leave" name="knob-reassign" value="n" checked="checked">Leave <br> 
<input type="radio" id="knob-reassign-cmp" name="knob-reassign" value="d"> Default <br> 
<input type="radio" id="knob-reassign-reassign" name="knob-reassign" value="r"> Reassign to 

<select name="assigned_to" id="assigned_to" onchange=" 
    if ((this.value != 'currentuser') && (this.value != '')) { 
    document.getElementById('knob-reassign-reassign').checked=true; 
    }"> 

    <option value="otheruser">Someone Else</option> 
    <option value="lastuser">Someone Third</option> 
    <option value="currentuser" selected="selected">Me</option> 
</select>