IE,getElementById和单选按钮

时间:2011-02-03 14:39:29

标签: internet-explorer radio-button 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和chrome中运行得很好,但正如我在编写代码时总是听到的,这在IE中不起作用。似乎IE正在搜索ID的“名称”,或者它试图将ID转换为名称,因为它总是选择第一个无线电,当它应该抓住最后一个。

1 个答案:

答案 0 :(得分: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>