0

我想检查html代码运行函数中是否有类.required_selectbox,html代码运行函数中required_selectbox()是否有类,提交后,怎么样?.requiredrequired_valid()

function required_valid() {
    $('.required').each(function () {
        if (!$(this).val()) {
            //var cssObj=;
            $(this).css("background", "#ffc4c4");
            result = false;
        } else {
            $(this).css("background", "#FFFFEC");
            result = true;
        }
        $(this).keyup(function () {
            $(this).css("background", "#FFFFEC");
        })
    });
    return result;
}

function required_selectbox() {
    $('.required_selectbox').each(function () {
        if (!$(this).val()) {
            //var cssObj=;
            $(this).css("background", "#ffc4c4");
            result = false;
        } else {
            result = true;
        }

    });
    return result;
}
$('.submit').submit(function () {
    //alert('hello');
    var passed = true;
    passed = required_selectbox() && passed;
    passed = required_valid() && passed;
    if (!passed) {
        return false;
    }
});
4

3 回答 3

1

一个简单的方法是运行这些函数,即使元素不存在。因为找不到任何元素,所以调用each()不会做任何事情,所以只需将result变量设置为true默认值:

function required_selectbox() {
    var result = true;  // <--- 
    $('.required_selectbox').each(function () {
        if (!$(this).val()) {
            //var cssObj=;
            $(this).css("background", "#ffc4c4");
            result = false;
        } else {
            result = true;
        }
    });
    return result;
}

此外,看起来您可能不希望该else语句在那里,因此您可能希望将其删除。

于 2011-10-09T10:51:46.717 回答
0
function required_valid() {
    var required = $('.required');
    required.css("background", "#FFFFEC");

    //Find any empty elements, and add the red style
    var empty = required.filter(function() {
        return $(this).val() == '';
    });
    empty.css("background", "#ffc4c4");

    //Did we find any empty elements?
    return empty.length > 0;
}

function required_selectbox() {
    var required = $('.required_selectbox');
    required.css("background", "#FFFFEC");

    //Find any empty elements, and add the red style
    var empty = required.filter(function() {
        return $(this).val() == '';
    });
    empty.css("background", "#ffc4c4");

    //Did we find any empty elements?
    return empty.length > 0;
}

$('.submit').submit(function() {
    return required_selectbox() && required_valid();
});
于 2011-10-09T10:56:13.820 回答
0

我不确定你想要什么帽子,但是——

 $('.required_selectbox').length

会让您知道.required_selectbox您的文档中是否有任何类元素。然后你可以做一个类似的事情required_valid

于 2011-10-09T10:52:20.503 回答