更有效地编写这个javascript的方法

前端之家收集整理的这篇文章主要介绍了更有效地编写这个javascript的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为我的网站创建一个联系表单,并在提交之前使用 javascript进行第一层验证,然后通过PHP再次检查,但我是相对较新的javascript,这是我的脚本…
$("#send").click(function() {
    var fullname = $("input#fullname").val();
    var email = $("input#email").val();
    var subject = $("input#subject").val();
    var message = $("textarea#message").val();
    if (fullname == ""){
        $("input#fullname").css("background","#d02624");
        $("input#fullname").css("color","#121212");
    }else{
        $("input#fullname").css("background","#121212");
        $("input#fullname").css("color","#5c5c5c");
    }
    if (email == ""){
        $("input#email").css("background","#d02624");
        $("input#email").css("color","#121212");
    }else{
        $("input#email").css("background","#121212");
        $("input#email").css("color","#5c5c5c");
    }
    if (subject == ""){
        $("input#subject").css("background","#d02624");
        $("input#subject").css("color","#121212");
    }else{
        $("input#subject").css("background","#121212");
        $("input#subject").css("color","#5c5c5c");
    }
    if (message == ""){
        $("textarea#message").css("background","#d02624");
        $("textarea#message").css("color","#121212");
    }else{
        $("textarea#message").css("background","#121212");
        $("textarea#message").css("color","#5c5c5c");
    }
    if (name && email && subject && message != ""){
        alert("YAY");
    }
});

如果所有字段都填写完整,我怎样才能更有效地写这个并发出警报显示,谢谢.

解决方法

$("#send").click(function() {
    var Failed = false;

    $('input#fullname,input#email,input#subject,textarea#message').each(function() {
        var item = $(this);
        if (item.val()) {
            item.css("background","#121212").css("color","#5c5c5c");
        } else {
            item.css("background","#d02624").css("color","#121212");
            Failed = true;
        }
    });

    if (Failed){
        alert("YAY");
    }
});

猜你在找的JavaScript相关文章