单选按钮:奇怪的选择行为

时间:2013-07-24 15:27:37

标签: javascript html

我一直在摸索这个问题一个小时了,我无法弄清楚为什么Radiobuttons出现这种奇怪的行为。以下是我的代码:

<label>Language
  <input type="radio" id="de" value="de" onclick="switchRadioButtons(this);" >de
  <input type="radio" id="en" value="en" onclick="switchRadioButtons(this);" >en
  <input type="radio" id="other" value="other" onclick="switchRadioButtons(this);" >other
  <input type="text" id="language" value="" /><br />
</label>

<script>
  function switchRadioButtons(element) {
    console.log(element.value);  
</script>

因此,在我看来,每当我点击值或按钮本身时,应将radiobutton的值写入控制台。这对于按钮本身是正常的,但如果我点击按钮旁边的标签/描述,它将始终打印“de”(第一项),无论我做什么(我也尝试过“switchRadioButtons(document.getElementById( '其他'));“没有效果。”

任何人都可以解释为什么会发生这种情况并提供解决方案吗?

2 个答案:

答案 0 :(得分:8)

您拥有相同标签内的所有输入!如果你点击它,它会触发第一个元素('de')。它不知道你想触发其他一个。

您需要为每个元素设置单独的标签。

答案 1 :(得分:2)

  • 在您的输入中添加一个组
  • 删除标签封闭输入
  • autoclose输入标签 xHTML thingy ......

Voilà有效:

http://jsfiddle.net/techunter/Z3fU7/

<强> HTML

<label for="de">Deutch</label>
<input type="radio" name="lang" id="de" value="de" onclick="switchRadioButtons(this);" />
<label for="en">English</label>
<input type="radio" name="lang" id="en" value="en" onclick="switchRadioButtons(this);" />
<label for="other">Other</label>
<input type="radio" name="lang" id="other" value="other" onclick="switchRadioButtons(this);" />
<input type="text" id="language" value="" />

<强> JS

function switchRadioButtons(element) {
    console.log(element.value);
}
相关问题