我一直在網上尋找答案,並沒有發現任何有用的東西。我正在一個網頁上編寫測驗。我沒有一個具有多個單選按鈕組的表單,而是多個表單,每個表單都有自己的單選按鈕組。每當我運行我的代碼來獲取每個表單中的值時,我就沒有比第一組更多的東西了。此後,我的函數調用的第二次迭代說我的表單字段的變量是未定義的。多個單選按鈕形式,單個組無法檢索值
呼叫的實施例,以形成值檢索代碼:的代碼形式和單選按鈕
function submit_quiz(){
var one, two, three;
one = getRadioValue(document.getElementById("ans1"), "a1");
alert(one);
one = getRadioValue(document.getElementById("ans2"), "a2");
alert(two);
one = getRadioValue(document.getElementById("ans3"), "a3");
alert(three);
}
function getRadioValue(form, name){
var val;
var i;
var f = form;
var n = name;
radios = f.elements[n];
len = radios.length;
for(i=0; i<len; i++){
if(radios[i].checked){
val = radios[i].value;
break;
}
}
return val;
}
實施例:
<ol class="quiz_question">
<li id="q1">
<p>According to Sun Tzu, the study of war is what to the state?</p>
<form class="answer_selections" id="ans1">
<input name="a1" value="1" type="radio" />A useless endeavor to be avoided.<br />
<input name="a1" value="2" type="radio" />Too costly to be of any practical use.<br />
<input name="a1" value="3" type="radio" />A matter of life and death.<br />
<input name="a1" value="4" type="radio" />Important to the state's wealth.<br />
</form>
</li>
<li id="q2">
<p>Sun Tzu says long wars have what effect?</p>
<form class="answer_selections" id="ans2">
<input name="a2" value="1" type="radio" />Both the state's wealth, and the army's strength wane.<br />
<input name="a2" value="2" type="radio" />Then enemy's strenght is steadily ground into nothing.<br />
<input name="a2" value="3" type="radio" />Both sides will eventually choose a mutually agreable peace.<br />
<input name="a2" value="4" type="radio" />There will be no effect as the war will become a stalemate.<br />
</form>
</li>
<li id="q3">
<p>If your army is five times as big as your enemies, what is your best course of action?</p>
<form class="answer_selections" id="ans3">
<input name="a3" value="1" type="radio" />Attempt to surround and destroy the enemy's forces.<br />
<input name="a3" value="2" type="radio" />Pull back, and wait for a better opportunity to attack.<br />
<input name="a3" value="3" type="radio" />Split your forces in two, and send one to attack the enemy's rear.<br />
<input name="a3" value="4" type="radio" />Attack immediatly, unless the enemy holds some other serious advantage.<br />
</form>
</li>
'二/ three'被聲明爲'undefined',其價值沒有被設置任何地方.. – Rayon