0

这是我验证 html 表的 jQuery 代码:

function validation() {

    var alertValidation = "";
    var _qid = "";
    var _msg = "";

    $("[class*='q']").each(function (i) {
        var questions = parseInt($("[class*=q" + i + "_qnum]").text());
        var marks = parseInt($("[class*=q" + i + "_ans_text]").text());
        var txtinput = $("[class*=q" + i + "_mark]").val();
        _qid = questions;
        _msg = "You have errors on Question Number: " + _qid + "\n";


        if (txtinput == '' || txtinput == null) {
            alertValidation += "\n\u2022 You have not entered in a value for all the Indivdiaul Marks textbox\n";
        } else if (marks < '0') {

            alertValidation = "Your Total Marks Remaining does not equal 0 \n\n\u2022 You Need To Remove " + Math.abs(marks) + " Marks";
        } else if (marks > '0') {

            alertValidation = "Your Total Marks Remaining does not equal 0 \n\n\u2022 You Have " + marks + " Marks Remaining";
        }

        if (alertValidation != "") {
            return false; //Stop the each loop 
        }

    });


    if (alertValidation != "") {
        alert(_msg + alertValidation);
        return false;
    }

    return true;
}

现在我觉得奇怪的是,如果剩余标记数高于 0 时的验证以及剩余标记数低于 0 时的验证在输出警报时完美运行,如下所示:

大于 0:

You have errors on Question Number: 1
Your Total Marks Remaining does not equal 0 

• You Have 7 Marks Remaining

小于 0:

You have errors on Question Number: 1
Your Total Marks Remaining does not equal 0 

• You Need To Remove 3 Marks

但是,当我尝试验证“每个答案的分数”部分下的文本输入是否为空时,它会在下面显示此消息:

You have errors on Question Number: NaN

• You have not entered in a value for all the Indivdiaul Marks textbox

为什么它不能显示此验证的问题编号?

我遇到的另一个小问题是,即使我在“每个答案的标记”下的所有文本输入中输入了一个值,它仍然会在不应该这样做时显示上述验证消息警报。为什么它也这样做?

下面是一个示例 html 表:

<table border='1' id='markstbl'>
<thead>
<tr>
<th class='questionth'>Question No.</th>
<th class='answermarksth'>Marks per Answer</th>
<th class='noofmarksth'>Marks Remaining</th>
</tr>
</thead>
<tbody>

<tr class="questiontd">
<td class="questionnumtd q<?php echo$questionId?>_qnum" name="numQuestion" rowspan="1">1 <input type="hidden" name="q1_ans_org" class="q1_ans_org" value="5"><input type="hidden" name="q1_ans" class="q1_ans" value="5"></td>
<td class="answermarkstd">
<input class="individualMarks q1_mark"  q_group="1" name="answerMarks[]" class="individualtext" type="text" onkeypress="return isNumberKey(event)" maxlength="3" />
</td>
<td class="noofmarkstd q1_ans_text"  q_group="1" rowspan="1"><strong>5</strong></td>
</tr>
    </tbody>
</table>
4

2 回答 2

0

尝试使用 alert($("[class*=q" + i + "_qnum]").text());

或使用 google chrome 或 firebug 进行调试,

我相信 each() 会捕获您的网络中不存在的类,或者它包含无法解析为 Int 的字符、空格,这会导致您的脚本中出现 NaN,请尝试检查一下

于 2012-12-05T07:30:14.813 回答
0

您可以使用 length 来检查属性是否有空文本而不是 != ""

alertValidation.length > 0

你能检查下面的代码吗

parseInt($("[class*=q" + i + "_qnum]").text());

如果此 $("[class*=q" + i + "_qnum]").text() 未定义,则 parseInt 将仅返回 NaN

谢谢

于 2012-12-05T03:53:52.973 回答