2010-10-22 47 views
0

在我的JavaScript程序中,我通過它的元素從表單中獲取值,然後按順序將它們打印在一個警報中。這在Firefox中運行良好,但在Chrome中,順序很古怪,並以「Submit」按鈕結束。Firefox認爲<fieldset>是一種表單元素; Chrome不是

我試圖擺脫字段和調整數字,它的工作,但我喜歡fieldset!此外,我不能只是製作一個數組並迭代它,因爲這些字段是按照Tab鍵順序調整的,我想相應地打印它們。有什麼建議麼?

在嘗試驗證後,我發現確實需要XHTML Strict的字段集。我一直在儲存數組中的元素,像這樣:

var $ = function (id) { return document.getElementById(id); } 

function check() { 
var x = $("myForm"); 

var user = new Array(); 
user[0] = x.elements[0].value; 
user[1] = x.elements[2].value; 
user[2] = x.elements[4].value; 
user[3] = x.elements[1].value; 
user[4] = x.elements[3].value; 
user[5] = x.elements[5].value; 

,然後用另一對夫婦陣列的檢查他們,並在彈出的顯示結果:

var answers = new Array(); 
answers[0] = "sample1"; 
answers[1] = "sample2"; 
answers[2] = "sample3"; 
answers[3] = "sample4"; 
answers[4] = "sample5"; 
answers[5] = "sample6"; 

var display = new Array(); 
for (var i=0;i<6;i++) { 
    if (user[i] == "") { 
     display[i] = "You entered nothing."; 
     } 
    else if (user[i] == answers[i]) { 
     display[i] = "Correct!"; 
     } 
    else { 
     display[i] = "Wrong. The correct answer is \"" + answers[i] + "\"."; 
     } 
    } 
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]); 
} 
+0

將問題添加到表單的HTML和JavaScript中。 – 2010-10-22 21:57:00

+0

調整*什麼*號碼?我懷疑這個問題是,Chrome以一些內部散列表順序給你提供了字段(這有點奇怪,因爲它在發佈表單時必須按順序發送它們)。 – Pointy 2010-10-22 22:22:29

+0

如果你不能創建一個數組(nodelist),你如何訪問實際的元素? – 2010-10-22 22:54:17

回答

0

我想你「會是使用的ID關好:

<form ...> 
    <input ... id="q0" /> 
    <input ... id="q1" /> 
    <input ... id="q2" /> 
</form> 

所以,你可以這樣寫JavaScript代碼:

var answers = new Array(); 
answers[0] = "sample1"; 
answers[1] = "sample2"; 
answers[2] = "sample3"; 
answers[3] = "sample4"; 
answers[4] = "sample5"; 
answers[5] = "sample6"; 

var display = new Array(); 
for (var i=0;i<6;i++) { 
    var user = $('q' + i).value; 
    if (user == "") 
    display[i] = "You entered nothing."; 
    else if (user == answers[i]) 
    display[i] = "Correct!"; 
    else 
    display[i] = "Wrong. The correct answer is \"" + answers[i] + "\"."; 
} 
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]); 

您的代碼可以收到很多的改進,太:

var answers = [ "sample1", "sample2", "sample3", "sample4", "sample5", "sample6" ]; 

var display = new Array(); 
for (var i=0;i<6;i++) { 
    var user = $('q' + i).value; 
    if (user == "") 
    display.push("You entered nothing."); 
    else if (user == answers[i]) 
    display.push("Correct!"); 
    else 
    display.push ("Wrong. The correct answer is \"" + answers[i] + "\"."); 
} 
alert(display.join('\n')); 
+0

非常感謝你,那很完美! – user460847 2010-10-23 23:12:31

相關問題