2013-07-24 42 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')。它不知道你想觸發其他的。

您需要爲分別標註元素。