2013-07-24 41 views
0

我一直在摸索这个问题一个小时了,我不知道为什么这个奇怪的行为在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> 

所以,在我看来,每当我点击任一值或按钮本身,单选按钮的值写入到控制台。这对按钮本身是正确的,但如果我点击标签/描述除了按钮,它总是会打印“德”(第一项),无论我做了什么(我也试过“switchRadioButtons(document.getElementById 'other'));“不起作用)。

任何人都可以解释为什么会发生这种情况,也许提供一个解决方案?

+0

输入的autoclosing标签和标签不能包含输入标签,你可能想先试试这种变化 – TecHunter

+0

Errr ......为什么所有的输入是由一个标签包围? – melancia

+2

输入是一个自闭标记与HTML 5无关。这是一个xHTML的东西。 – melancia

回答

2
  • 将组添加到您的输入
  • 删除标签封装输入
  • 自动关闭输入标签 的xHTML啄...

瞧它的工作原理:

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); 
} 
8

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

您需要为分别标注元素。