简体   繁体   English

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

[英]More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script... 我正在为我的网站创建一个联系表单,并在提交之前使用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");
    }
});

How can i write this more efficiently and make the alert show if all the fields are filled out, thanks. 如果所有字段都填写好,我怎样才能更有效地写这个并发出警报显示,谢谢。

$("#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");
    }
});

glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation. glavic和matt的答案正是我要提出的建议,除了我会通过将逻辑与演示文稿分开来更进一步。

Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass() 在字段中包含无效条目时,在css中定义类,并使用$.addClass()$.removeClass()添加或删除该类

Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required"). 由于您使用的是jQuery,我建议在每个需要非空值的字段上设置一个类(class =“required”)。

Then you do something like this: 然后你做这样的事情:

var foundEmpty = false;
$(".required").each(function()
{
   if($(this).val())
   {
       foundEmpty=true;
       $(this).style("background-color", "red");
   }
});
if(foundEmpty)
{
  alert("One or more fields require a value.");
}

Giving them a common class, define classes to apply the styles, and do this: 为它们提供一个公共类,定义应用样式的类,并执行以下操作:

JS JS

$("#send").click(function() {
    $('.validate').attr("class", function() {
        return $(this).val() === "" ? "validate invalid" : "validate valid";
    });
    if( $('.invalid').length === 0 ) {
        alert('YAY');
    }
});

CSS CSS

.valid {
    background:#121212;
    color:#5c5c5c
}

.invalid {
    background:#d02624;
    color:#121212;
}

HTML HTML

<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">

JSFIDDLE DEMO JSFIDDLE DEMO


A little bit more efficient approach: 更有效的方法:

var validate = $('.validate');

$("#send").click(function() {
    validate.attr("class", function() {
        return $(this).val() === "" ? "validate invalid" : "validate valid";
    });
    if( validate.filter('.invalid').length === 0 ) {
        alert('YAY');
    }
});

You can use jQuery to iterate over each object and get their values. 您可以使用jQuery迭代每个对象并获取它们的值。 Depending on your form, this code will change, but it's to give you an example. 根据您的表单,此代码将更改,但它是为您提供示例。 I'm probably missing a couple of brackets here and there but the concept is there. 我可能在这里和那里都缺少几个括号,但概念就在那里。

var objectName=$(this).attr('id');    
$('#formId').children().each(
        function(){

            if ($(this).value == ""){
                 $(this).css("background","#d02624");
                 $(this).css("color","#121212");
                 $error[objectName]='true';

            }else{
                 $(this).css("background","#121212");
                 $(this).css("color","#5c5c5c");
                 $error[objectName]='false';
            }




        }
    );
           $.each(error, function(key, value){


                if (value=='false'){
                  alert (key + 'is empty');
                }
           });

I would probably divide part of this up into my css file. 我可能会把它的一部分分成我的css文件。 If any of the fields are empty add a class like "empty" to the object, if not, remove it. 如果任何字段为空,则向对象添加类似“empty”的类,如果没有,则将其删除。 Then in your css file you can add some descriptors like: 然后在你的css文件中你可以添加一些描述符,如:

input#fullname,
input#email {
   ...
}

input#fullname.empty,
input#email.empty {
    ...
}

You can use jQuery addClass() and removeClass(). 您可以使用jQuery addClass()和removeClass()。

You can then add a loop as follows: 然后,您可以按如下方式添加循环:

var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
    var value = $(inputs[0]).val();
    if (value.length > 0) {
        $(inputs[i]).removeClass("empty");
    } else {
        complete = false;
        $(inputs[i]).addClass("empty");
    }
}
if (complete) {
}

EDIT: 编辑:

There you go, fixed it for you. 你去,为你修好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM