我正在提出問題和答案的應用程序。功能來檢查多個可能的字段
http://jsfiddle.net/kaninepete/4YTA6/
我怎麼能擴大這個允許同一類型的不止一個問題嗎?
我不知道讓功能知道女巫領域檢查。
在此先感謝。
編輯 我想單獨檢查每個答案。 這是否需要每個問題的新表單?
我正在提出問題和答案的應用程序。功能來檢查多個可能的字段
http://jsfiddle.net/kaninepete/4YTA6/
我怎麼能擴大這個允許同一類型的不止一個問題嗎?
我不知道讓功能知道女巫領域檢查。
在此先感謝。
編輯 我想單獨檢查每個答案。 這是否需要每個問題的新表單?
這在技術上有效,但可能會使用相當多的清理 - 建設性的批評歡迎。 (使HTML文件真正有效,不要直接鏈接到jQuery,清理我的jQuery等等等等。我還不是jQuery專家。)我去了JavaScript查看所有合適的HTML並顯示響應的路線(而不是構建基於HTML關閉JavaScript數組的。)
你基本上可以複製 - 粘貼<li>...</li>
的東西,改變下列每題q-
和a-
的數量,它會工作。
理想情況下,我們會使用服務器端編程,以驗證答案(因爲客戶可以方便地查看答案。)
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js" ></script>
</head>
<body>
<form name="myform" id="myform">
<p>Make each of the following possessive by adding the appropriate apostrophe where needed. </p>
<ol type="1">
<li>boys:
<input type="text" name="q-1" /><!-- field for user input -->
<input type="hidden" name="a-1" value="boy's" /><!-- answer -->
</li>
<li>girls:
<input type="text" name="q-2" />
<input type="hidden" name="a-2" value="girl's" />
</li>
</ol>
<p><input type="button" id="validate-btn" value="Check" /></p>
</form>
<script type="text/javascript">
$('document').ready(function() {
$('#validate-btn').click(function() {
$(this).css('display','none');
$('[name|="q"]').each(function() {
// find the associated answer
var pattern = /q\-([0-9]+)/; // regular expression to pull question/answer number from field name
var result = pattern.exec($(this).attr('name'))[1]; // get the question/answer number
// you could probably just navigate around with DOM to get the next hidden text field instead, eh.
// get reference to the input with the answer
var answerbox = $('[name="a-'+result+'"]');
$(this).attr('disabled',true);
// verify answer, display replacement text
if($(this).val() == answerbox.val()) {
$(this).replaceWith(' <strong>Correct!</strong>');
} else {
$(this).replaceWith(' <strong>Incorrect! The answer was "'+ answerbox.val() +'"</strong>');
}
});
});
});
</script>
</body>
它不喜歡這樣會單獨檢查每個問題。 我不完全明白你的答案,但我現在正在玩弄它。 – Kaninepete 2011-04-07 01:26:59
僅供參考,'id'屬性可能不合法地啓動一個號碼。 – Phrogz 2011-04-06 23:17:11
當你添加更多的問題時,他們會一樣的「添加撇號」問題,還是完全不同的問題?另外,你是否只想將JavaScript中定義的問題當作一個數組,然後從那裏神奇地構建HTML,或者僅僅基於隱藏的表單字段在HTML中提供一些JavaScript驗證問題?只是把想法扔出去。 – Guttsy 2011-04-07 00:20:45
更多相同的格式。 我可以做一個數組, 我只是打字試試。 我真正的問題是讓函數在需要時一次驗證一個字段,而不是一次全部驗證任何字段。 – Kaninepete 2011-04-07 00:33:42