0

下面我使用了一个 for 循环来遍历每个问题:

for (var i=0;i<=questions;i++){   
    if ($("[class*=q" + i + "_mark]").length == 1) {
        var bold_marks='<strong>0</strong>';
        var t_marksHtml = t_marks.val();
        $("[class*=q" + i + "_mark]").val(t_marksHtml).attr('readonly', true);
    }                    
}

现在我想做的是创建一个验证函数,以便它通过每个问题和每个问题中的每个元素进行验证,但问题是我试图使用 foreach 函数循环遍历每一行,如下所示:

function validation() {

    var alertValidation = "";
    var _qid = "";
    var _msg = "";
    var marks = parseInt($("[class*=q" + i + "_mark]").text()); 

    _qid = $(".q"+questionno+"_ans_org").text();
    _msg = "You have errors on Question Number: " + _qid + "\n";

$("[class*=q" + i + "_mark]").each(function() {

if (!this.value) {
    alertValidation += "\n\u2022 You have not entered in a value in the Indivdiaul Marks textbox all your Answers\n";
}

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

     $(".q"+questionno+"_ans_org").each(function(){


if($("[class*=q" + i + "_mark]").text() < '0')
{

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

        else if($("[class*=q" + i + "_mark]").text() > '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;
}

显然因为我使用的是 foreach 方法,所以i未定义。现在我的问题是,首先,如果我对上面的验证函数使用 foreach 循环或 for 循环会更好吗?有人知道如何修复上面的代码,这样代码才能正常工作,这样我就不会得到i未定义的错误?

下面是html代码:

<table border='1' id='markstbl'>
<thead>
<tr>
<th class='answermarksth'>Marks per Answer</th>
<th class='totalmarksth'>Total Marks</th>
<th class='noofmarksth'>Marks Remaining</th>
</tr>
</thead>
<tbody>

<tr class="questiontd">
<td class="answermarkstd">
<input class="individualMarks q1_mark_0"  q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<td class="totalmarkstd" rowspan="2">6</td>
<td class="noofmarkstd q1_ans_text"  q_group="1" rowspan="2"><strong>5</strong></td>
</tr>

<tr class="questiontd">
    <td class="answertd" name="answers[]">D</td>
<td class="answermarkstd">
<input class="individualMarks q1_mark_0"  q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
</tr>

<tr class="questiontd">
<td class="answermarkstd">
<input class="individualMarks q2_mark_0"  q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<td class="totalmarkstd" rowspan="1">6</td>
<td class="noofmarkstd q2_ans_text"  q_group="1" rowspan="1"><strong>5</strong></td>
</tr>
</tbody>
</table>
4

1 回答 1

0

代替

$("[class*=q" + i + "_mark]").each(function() {

只需使用

$("[class*='q'").each(function(i) {

循环将i in the $.each是迭代的当前输入类。

对其他循环也遵循相同的方法..

于 2012-12-03T20:45:19.113 回答