Javascript 函数检查多个可能的字段

Javascript 函数检查多个可能的字段,javascript,dom,submit,field,Javascript,Dom,Submit,Field,我正在做一个问答申请 我如何扩展它以允许同一类型的多个问题 我不知道要让函数知道要检查的开关域 提前谢谢 编辑 我想逐一核对每个答案。 这是否需要为每个问题提供一个新的表单?是的,您需要为每个问题提供一个新的元素,以便用户回答。这在技术上可行,但可能需要进行大量清理-欢迎建设性的批评。使HTML文件实际有效,不要直接链接到jQuery,清理我的jQuery等等。我还不是jQuery专家。我走的路线是JavaScript查看所有适当的HTML并显示响应,而不是基于JavaScript数组构建HTM

我正在做一个问答申请

我如何扩展它以允许同一类型的多个问题

我不知道要让函数知道要检查的开关域

提前谢谢

编辑 我想逐一核对每个答案。
这是否需要为每个问题提供一个新的表单?

是的,您需要为每个问题提供一个新的元素,以便用户回答。

这在技术上可行,但可能需要进行大量清理-欢迎建设性的批评。使HTML文件实际有效,不要直接链接到jQuery,清理我的jQuery等等。我还不是jQuery专家。我走的路线是JavaScript查看所有适当的HTML并显示响应,而不是基于JavaScript数组构建HTML

你基本上可以复制粘贴。。。填充并更改每个问题的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('&nbsp; &nbsp;<strong>Correct!</strong>');
                    } else {
                        $(this).replaceWith('&nbsp; &nbsp;<strong>Incorrect! The answer was "'+ answerbox.val() +'"</strong>');
                    }
                });
            });
        });
    </script>
</body>

仅供参考,id属性在法律上不能以数字开头。当您添加更多问题时,它们是相同的添加撇号问题,还是完全不同的问题?另外,您是希望JavaScript中定义的问题作为一个数组,然后从那里神奇地构建HTML,还是简单地让一些JavaScript验证问题基于。。。隐藏表单字段?只是把想法扔出去。更多的是相同的格式。我可以制作一个数组,我只是打了这个来试试。我真正的问题是让函数在需要时一次验证一个字段,而不是一次验证所有字段或任何东西。不过,我不知道要在函数中更改什么以允许更多的问题。这样做不会单独检查每个问题。我不完全明白你的答案,但我现在在胡闹。