0

因此,在一个表格中,我有多项选择,因此我需要验证一系列答案。我对代码的尝试是这样的,但它只是返回未定义“i”(来自 .each() 行):

function validTextAnswers(i, answer){
    var answer = $j(this) 
    // ^ may not be needed, but I was using it 
    // when I was not passing arguements
    if( (answer.val()=="") || (textAnswers.val()==null )){
        alert('Note: Please fill in all answers.'),
        answer.focus()
        return false;
    } 
    return true;
}

function validQuizCreate(){
    var course = $j('#course-selection .selected')
    var question = $j('textarea[name="question"]')
    var textAnswers = $j('div.answer:visible').children('input[type="text"]');

    if( (question.val()=="") || (question.val()==null) ){
        alert('You have to supply a question.'),
        question.focus()
        return false;
    }

if( !textAnswers.each(validTextAnswers(i, answer)) ){
    console.log('all seems good!')
    return false
}

我已经玩了很多代码,只是当我这样做时它只是破坏了 jQuery。(注:假设 $j 为 $,这是为了避免与网站另一部分的原型发生冲突。)

解决方案

// jQuery filter() can be used for this:
var validTextAnswers = textAnswers.filter(function(){
        return this.value != '';
    }).length == '4'; // four because the test is A though D.

// If all 4 multiple choice answers are not empty, it returns true.

// so to use it I can say:
    if(!validTextAnswers){
        alert('Please fill in all multiple choice options.')
        return false;
    }
4

2 回答 2

0

each返回一个 jQuery 对象,它总是一个“真实的”值。

您可以使用filter

var isValid = textAnswers.filter(function() {
    return this.value == "invalild"
}).length > 0;

if (!isValid) {
    alert('PROBLEM!!!');
}​
于 2012-09-28T02:32:22.450 回答
-3

each接受一个函数参数,您正在调用该函数并传递其返回值。

请参阅jQuery 文档each()了解正确用法。

于 2012-09-28T02:29:20.867 回答