我正在提出问题和答案的应用程序。功能来检查多个可能的字段
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