我在循环中得到一个未定义的错误

时间:2012-12-03 20:42:40

标签: jquery html

下面我使用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函数循环遍历每一行,如下所示: / p>

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>

1 个答案:

答案 0 :(得分:0)

而不是

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

只需使用

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

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

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