简体   繁体   English

结合两个javascript函数?

[英]Combine two javascript functions?

How can I combine these two functions so that they both work? 我如何结合这两个功能,以便它们都可以工作? Right now, I can only get one to validate and not the other. 目前,我只能让一个人进行验证,而不能让另一个人进行验证。

SAMPLE OF THE JAVASCRIPT: JAVASCRIPT的示例:

function validateForm() {

var x=document.forms["giftCert"]["gift_name"].value;

if (x==null || x=="") {

errMsg = "The recpient's name is required.";              
    $("div#emptyName").show();
    $("div#emptyName").html(errMsg);

return false;
  }
}

function validateForm() {

var x=document.forms["giftCert"]["gift_email"].value;

if (x==null || x=="") {

errMsg2 = "The recpient's email address is required.";              
    $("div#emptyEmail").show();
    $("div#emptyEmail").html(errMsg2);

return false;
  }
}

SHORT VERSION OF THE FORM HTML: 表单HTML的简短版本:

<form action="http://ww6.aitsafe.com/cf/voucher.cfm" method="post" name="giftCert" onsubmit="return validateForm()"  />
    *Name:<input type="text" name="gift_name">
    <div id="emptyName" class="error"></div>

    *Email: <input type="text" name="gift_email">
    <div id="emptyEmail" class="error"></div>

    <input class="button" type="submit" value="Add to Cart" />

</form>

You can put the code in the same function. 您可以将代码放在相同的函数中。

function validateForm() {
    return ["Name", "Email"].every(function(type) {
        var lower_type = type.toLowerCase(),
            x=document.forms["giftCert"]["gift_" + lower_type].value;

        if (x==null || x=="")
            $("div#empty" + type).show().html("The recpient's " + lower_type + " is required.");
        else
            return true;
    });
}

Since much of the code is nearly identical, you can put the "Name" and "Email" values in an Array, and loop the Array, invoking the identical code, dropping in the appropriate value where needed. 由于大多数代码几乎是相同的,因此可以将"Name""Email"值放在数组中,然后循环数组,调用相同的代码,并在需要的地方添加适当的值。

This uses the Array.prototype.every to indicate if each value in the Array passed validation. 这使用Array.prototype.every来指示Array中的每个值是否通过验证。

If either item fails validation, it returns undefined , the loop halts and validateForm returns false . 如果任何一项验证失败,则返回undefined ,循环暂停, validateForm返回false

Every item that passes validation returns true . 每个通过验证的项目都将返回true If all items pass validation, .every will return true , and the form proceeds. 如果所有项目均通过验证, .every将返回true ,然后继续执行表单。


If you want to make sure all the validations run, you can use .filter() , and return true on a failure, so that it will add an item to the resulting Array. 如果要确保运行所有验证,则可以使用.filter() ,并在失败时返回true ,以便它将一个项添加到生成的Array中。 If there were no failures, the Array will be empty. 如果没有故障,则阵列将为空。

Then test the .length of the Array, and return a comparison to 0 . 然后测试Array的.length ,并返回与0的比较。

function validateForm() {
    return ["Name", "Email"].filter(function(type) {
        var lower_type = type.toLowerCase(),
            x=document.forms["giftCert"]["gift_" + lower_type].value;

        if (x==null || x=="") {
            $("div#empty" + type).show().html("The recpient's " + lower_type + " is required.");
            return true;
        }
    }).length === 0; // will be true if no validation failures
}

Have it call the second one when done. 完成后让它调用第二个。

Or have a 3rd function that calls both of them and have that in your onsubmit. 或者有一个第三个函数调用它们,并在您的onsubmit中包含它们。 That function will see the return values of both functions and return true only if both of them return true. 该函数将看到两个函数的返回值,并且仅在两个函数都返回true时才返回true。

Or just put the code of the second one inside the first, since it's similar anyway. 或者只是将第二个的代码放在第一个的内部,因为无论如何它们都是相似的。 You can get rid of some of duplicate code too. 您也可以摆脱一些重复的代码。

When you reuse the same function name, each succeeding function declaration will overwrite any preceding entries. 当您重复使用相同的函数名称时,每个后续函数声明都将覆盖之前的所有条目。 It might be easiest to keep your validations in separate functions, so you should name them appropriately and create a driver function to call them all. 将验证保存在单独的函数中可能是最容易的,因此您应该适当地命名它们并创建一个驱动程序函数以全部调用它们。 Example: 例:

function validateForm() {
  return validateName && validateEmail();
}

function validateName() {

  var x=document.forms["giftCert"]["gift_name"].value;

  if (x==null || x=="") {

    errMsg = "The recpient's name is required.";              
    $("div#emptyName").show();
    $("div#emptyName").html(errMsg);

    return false;
  }

  return true;
}

function validateEmail() {

  var x=document.forms["giftCert"]["gift_email"].value;

  if (x==null || x=="") {

    errMsg2 = "The recpient's email address is required.";              
    $("div#emptyEmail").show();
    $("div#emptyEmail").html(errMsg2);

    return false;
  }

  return true;
}

Additionally, you can just combine the two, but this isn't nearly as flexible: 此外,您可以将两者结合使用,但这并不那么灵活:

function validateForm() {

  var name =document.forms["giftCert"]["gift_name"].value;

  if (name == null || name == "") {

    errMsg = "The recpient's name is required.";              
    $("div#emptyName").show();
    $("div#emptyName").html(errMsg);

    return false;
  }

  var email = document.forms["giftCert"]["gift_email"].value;

  if (email == null || email == "") {

    errMsg2 = "The recpient's email address is required.";              
    $("div#emptyEmail").show();
    $("div#emptyEmail").html(errMsg2);

    return false;
  }

  return true;
}

The short answer is just do this 简短的答案就是这样做

function validateForm() {

var x=document.forms["giftCert"]["gift_name"].value;

if (x==null || x=="") {

    errMsg = "The recpient's name is required.";              
    $("div#emptyName").show();
    $("div#emptyName").html(errMsg);

    return false;
}
x=document.forms["giftCert"]["gift_email"].value;

if (x==null || x=="") {

    errMsg2 = "The recpient's email address is required.";              
    $("div#emptyEmail").show();
    $("div#emptyEmail").html(errMsg2);

   return false;
  }
}

The longer answer is your functions have to have unique names. 更长的答案是您的函数必须具有唯一的名称。 Also, you use jquery in part of your code why not use it to access your forms? 另外,您在代码的一部分中使用了jQuery,为什么不使用它来访问表单? Also, it usually considered bad practice to call your functions from the HTML. 同样,从HTML调用函数通常被认为是不好的做法。

One possible solution: 一种可能的解决方案:

function validateForm() {

    var x=document.forms["giftCert"]["gift_name"].value,
        y = document.forms["giftCert"]["gift_email"].value,
        error = false;

    if ( !x ) {
        errMsg = "The recpient's name is required.";              
        $("div#emptyName").html(errMsg).show();
        error = true;
    }

    if ( !y ) {
        errMsg2 = "The recpient's email address is required.";              
        $("div#emptyEmail").html(errMsg2).show();
        error = true;
    }

    if (error === true) return false;

}​

For anyone wondering how to combine two functions into one, here's a function I created for doing this: 对于想知道如何将两个函数组合为一个的任何人,这是我为此创建的一个函数:

function combineFunctions() {
    var args = Array.prototype.slice.call(arguments, 0);
    return function() {
            for (var i = 0, len = args.length; i < len; i++) {
                if (typeof args[i] === "function") {
                    args[i].apply(this, arguments);
                }
            }
    };
}

Then to combine to functions: 然后合并为功能:

var myFunc = function() { console.log('1'); };
var myOtherFunc = function() { console.log('2'); };

var myCombinedFunc = combineFunctions(myFunc, myOtherFunc);
myCombinedFunc(); // outputs 1, then 2 to the console

Note: This only works for functions with the same arguments -- works great for adding a function to an event handler 注意:这仅适用于具有相同参数的函数-适用于将函数添加到事件处理程序

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

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