Javascript 检查多个函数是否为真,然后做一些事情

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4424191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:21:13  来源:igfitidea点击:

Check if multiple functions are true, then do something

javascriptfunctionreturn-valuereturnform-submit

提问by Siriss

I am stuck on what I thought was a simple PEBCAK error on my part. I am trying to verify all of my functions are true before I submit a form, but cannot figure for the life of me what is wrong. Below is my javascript code:

我坚持认为我认为是一个简单的 PEBCAK 错误。在提交表单之前,我试图验证我的所有功能是否正确,但我终生无法弄清楚出了什么问题。下面是我的 javascript 代码:

function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
    return true;
}
else{
    return false;
}
}


function emailvalid()
{
      if(email condition)
      {
          return true;
      }
      else {
          return false;
      }
}

function checkname())
{
      if(name condition)
      {
          return true;
      }
      else {
          return false;
      }
}

function passwordcheck(){
      if(password condition)
      {
          return true;
      }
      else {
          return false;
      }
}

html below:

html如下:

<form  id="newaccount" name="newaccount" method="post"  onSubmit="accountcode.php">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password"  onkeyup="passwordcheck()"/>
<input type="submit" value="New" onClick="return checknewaccount()"/>
</form>

When i click "New, nothing happens, and I know the accountcode.php is not running, because nothing happens on the database end and there are no errors reported.

当我单击“新建”时,没有任何反应,我知道 accountcode.php 没有运行,因为数据库端没有任何反应,也没有报告错误。

To sum up, my question is how checknewaccount() does not work? Does it have something to do with how I am calling them?

总而言之,我的问题是 checknewaccount() 如何不起作用?这与我如何称呼他们有关吗?

I am new to javascript so if I am completely off on my implementation, I apologize. Thank you very much for the help!

我是 javascript 新手,所以如果我完全不了解我的实现,我深表歉意。非常感谢你的帮助!

采纳答案by Basic

you've got the form syntax wrong - onsubmit = the name of the js function to call, action = the url...

你的表单语法错误 - onsubmit = 要调用的 js 函数的名称,action = url ...

<form action="accountcode.php" id="newaccount" name="newaccount" method="post"  onSubmit="return checknewaccount()">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password"  onkeyup="passwordcheck()"/>
<input type="submit" value="New"/>
</form>

Fully tested code:

完全测试代码:

<html>
    <head>
        <script type="text/javascript">
        function checknewaccount() {
            return emailvalid() && checkname() && passwordcheck();
        }

        function emailvalid() {
             var emailAddress = document.getElementById('email').value;
             return (emailAddress=='test');
        }

        function checkname() {
             return true;
        }

        function passwordcheck() {
             return true;
        }

        </script>
    </head>
    <body>
    <form action="#" onsubmit="return checknewaccount();">
        <input type="text" id="email" name="email"/>
        <input type="submit"/>
    </form>
    </body>
</html>

The form in the above code will only submit if the textbox has a value of test

上面代码中的表单只有在文本框的值为test 时才会提交

A slightly better implementation would be:

稍微好一点的实现是:

<html>
    <head>
        <script type="text/javascript">
        function checknewaccount() {
            if(emailvalid() && checkname() && passwordcheck()) {
                return true;
            } else {
                document.getElementById('validation').innerHTML = 'Validation failed!';
                return false;
            }
        }

        function emailvalid() {
             var emailAddress = document.getElementById('email').value;
             return (emailAddress=='test');
        }

        function checkname() {
             return true;
        }

        function passwordcheck() {
             return true;
        }

        </script>
    </head>
    <body>
    <div id="validation"></div>
    <form action="#" onsubmit="return checknewaccount();">
        <input type="text" id="email" name="email"/>
        <input type="submit"/>
    </form>
    </body>
</html>

As this at least tells the user the form wasn't submitted. Even better would be to give the user a more detailed reason why but that's beyond the scope of this question...

因为这至少告诉用户表单没有提交。更好的是给用户一个更详细的原因,但这超出了这个问题的范围......

回答by T.J. Crowder

This part's fine (I took the liberty of fixing the indentation):

这部分很好(我冒昧地修复了缩进):

function checknewaccount(){
    if(emailvalid()&& checkname() && passwordcheck())
    {
        return true;
    }
    else{
        return false;
    }
}

Although you could improve it:

虽然你可以改进它:

function checknewaccount(){
    return emailvalid() && checkname() && passwordcheck();
}

This part is a syntax error (to put it mildly):

这部分是语法错误(说得客气一点):

function emailvalid(), checkname(), passwordcheck(){
if(condition){
    return true;}
else{return false;}
function emailvalid(), checkname(), passwordcheck(){
if(condition){
    return true;}
else{return false;}

If that's not a real quote from your code, you'll have to update your question (though I may not be here by then to update this answer). Not much point in asking about code and then quoting pseudo-code in the question. (At the very least, the pseudo-code is missing the final }.)

如果这不是您代码中的真实引用,您将不得不更新您的问题(尽管那时我可能不会在这里更新此答案)。询问代码然后在问题中引用伪代码没有多大意义。(至少,伪代码缺少最后的}.)

The same sort of thing is true for your functions in the form:

对于以下形式的函数,情况也是如此:

function emailvalid()
{
      if(email condition)
      {
          return true;
      }
      else {
          return false;
      }
}

That's fine (assuming that email conditionis stillpsuedocode), but there's no need for the if:

没关系(假设它仍然email condition是伪代码),但是不需要:if

function emailvalid()
{
    return email condition;
}

In terms of "nothing happens," make sure you have debugging tools you can use. Chrome has Dev Tools built in, just press Ctrl+Shift+I. For Firefox, you can install the excellent Firebug. Recent versions of IE have dev tools built into them as well (for older versions you can download a free version of Visual Studio that can plug into the browser). Any of these will tell you about syntax and other errors, let you walk through your code statement-by-statement, etc., which is crucial to figuring out what's happening.

就“什么也没发生”而言,请确保您有可以使用的调试工具。Chrome 内置了开发工具,只需按 Ctrl+Shift+I。对于 Firefox,您可以安装优秀的 Firebug。最新版本的 IE 也内置了开发工具(对于旧版本,您可以下载可插入浏览器的免费版 Visual Studio)。这些中的任何一个都会告诉您有关语法和其他错误的信息,让您逐个语句地浏览代码等,这对于弄清楚发生了什么至关重要。

Here's a quickly dashed-off version of what I think you're trying to do. I wouldn't do it this way, but I've made the minimal changes to make it work:

这是我认为你正在尝试做的一个快速破灭的版本。我不会这样做,但我做了最小的更改以使其正常工作:

HTML:

HTML:

<form action="http://www.google.com/search"
      method="GET" target="_blank"
      onsubmit="return checknewaccount()">
<input type="text" id="email" name='q' onblur="emailvalid()">
<input type="text" id="username" onblur="checkname()" >
<input type="password" id="password"  onkeyup="passwordcheck()">
<input type="submit" value="New">
</form>

Notes on that:

对此的注意事项:

  • As Basiclife pointed out, your formcode has issues. Those are fixed above.
  • Above I've used action="http://www.google.com/search"but of course for you it would be action="accountcode.php"(or at least, I think it would).
  • Use onsubmitfor the form submission handler, not onclickon the submit button. You can't cancel a form submission reliably cross-brower via the submit button's onclick.
  • In onsubmit, make sure you use return — e.g., onsubmit="return checknewaccount()", not onsubmit="checknewaccount()" — because we want to make sure the event stuff sees the return value. We don't care if the event stuff doesn't see the return value of our other checks (onblur="emailvalid()"), but if we did, we'd need returns there as well.
  • Only one of the fields above has a nameattribute; none of yours do. Only fields with nameattributes get submitted with forms. I've only used one namefor my example because I only want to submit one field to Google, but for your purposes, you're going to want nameattributes on all three fields. This brief articlehas a discussion of idvs. nameand what they're for. You sometimes want both.
  • I've put the attributes in all lower-case, which is best practice (and required if you want to use XHTML).
  • However, I've removed the /from the ends of the inputs. This is a bit off-topic, but at the apparent level you're working at, you don't want to try to use XHTML, use HTML. Using XHTML correctly is technically difficult, both in authoring and server configuration, and even then you have to serve it as tag soup to IE or it won't handle it properly. XHTML has its place, but in the vast majority of cases, there's no reason to use it.
  • With the above combined with the JavaScript below, there's no purpose whatsoever to the handlers on the individual fields. I've left them, though, because I assume you're doing more than just the checks below — there's an example further down showing those handlers doing something useful.
  • 正如Basiclife 指出的那样,您的form代码有问题。上面这些是固定的。
  • 以上我已经使用过,action="http://www.google.com/search"但当然对你来说会是action="accountcode.php"(或者至少,我认为会)。
  • 使用onsubmit的表单提交处理程序,而不是onclick提交按钮。您无法通过提交按钮的onclick.
  • 在 中onsubmit,确保您使用return - 例如,onsubmit="return checknewaccount()",不要onsubmit="checknewaccount()" - 因为我们要确保事件内容看到返回值。我们不在乎事件内容是否没有看到我们其他检查的返回值 ( onblur="emailvalid()"),但如果我们看到了,我们也需要returns 在那里。
  • 上述字段中只有一个具有name属性;你的都没有。只有具有name属性的字段才会随表单一起提交。我仅name在示例中使用了一个字段,因为我只想向 Google 提交一个字段,但出于您的目的,您将需要name所有三个字段的属性。这篇简短的文章讨论了idvs.name以及它们的用途。有时你两者都想要。
  • 我已将属性全部小写,这是最佳实践(如果您想使用 XHTML,这是必需的)。
  • 但是,我已经/inputs. 这有点题外话,但是在您工作的明显级别上,您不想尝试使用 XHTML,而是使用 HTML。正确使用 XHTML 在技术上是困难的,无论是在创作还是服务器配置方面,即便如此,您也必须将其作为标签汤提供给 IE,否则它无法正确处理。XHTML 有它的位置,但在绝大多数情况下,没有理由使用它。
  • 将上面的内容与下面的 JavaScript 结合起来,各个字段上的处理程序没有任何意义。不过,我已经离开了它们,因为我认为您所做的不仅仅是下面的检查——下面有一个示例显示这些处理程序正在做一些有用的事情。

JavaScript:

JavaScript:

function checknewaccount() {
  return emailvalid() && checkname() && passwordcheck();
}

function emailvalid() {
  var element;

  // Get the email element
  element = document.getElementById('email');

  // Obviously not a real check, just do whatever your condition is
  return element.value.indexOf('@') > 0;
}

function checkname() {
  var element;

  // Get the username element
  element = document.getElementById('username');

  // Obviously not a real check, just do whatever your condition is
  return element.value.length > 0;
}

function passwordcheck() {
  var element;

  // Get the username element
  element = document.getElementById('password');

  // Obviously not a real check, just do whatever your condition is
  return element.value.length > 0;
}

Live copy

实时复制

Things change slightly if the emailvalid, et. al., functions are going to do something to let the user know the fields are invalid, such as highlighting their labels:

如果emailvalid, et。al.,函数将做一些事情让用户知道这些字段是无效的,例如突出显示它们的标签:

HTML:

HTML:

<form action="http://www.google.com/search"
      method="GET" target="_blank"
      onsubmit="return checknewaccount()">
<label>Email:  
<input type="text" id="email" name='q' onblur="emailvalid()"></label>
<br><label>Username:
<input type="text" id="username" onblur="checkname()" ></label>
<br><label>Password:
<input type="password" id="password"  onkeyup="passwordcheck()"/></label>
<br><input type="submit" value="New">
</form>

JavaScript:

JavaScript:

function checknewaccount() {
  var result;
  // Because we're actually doing something in each of the
  // three functions below, on form validation we want to
  // call *all* of them, even if the first one fails, so
  // they each color their field accordingly. So instead
  // of a one-liner with && as in the previous example,
  // we ensure we do call each of them:
  result = emailvalid();
  result = checkname() && result;
  result = passwordcheck() && result;
  return result;
}

function emailvalid() {
      var element, result;

  // Get the email element
  element = document.getElementById('email');

  // Obviously not a real check, just do whatever your condition is
  result = element.value.indexOf('@') > 0;

  // Update our label and return the result
  updateLabel(element, result);
  return result;
}

function checkname() {
  var element, result;

  // Get the username element
  element = document.getElementById('username');

  // Obviously not a real check, just do whatever your condition is
  result = element.value.length > 0;

  // Update our label and return the result
  updateLabel(element, result);
  return result;
}

function passwordcheck() {
  var element, result;

  // Get the username element
  element = document.getElementById('password');

  // Obviously not a real check, just do whatever your condition is
  result = element.value.length > 0;

  // Update our label and return the result
  updateLabel(element, result);
  return result;
}

function updateLabel(node, valid) {
  while (node && node.tagName !== "LABEL") {
    node = node.parentNode;
  }
  if (node) {
    node.style.color = valid ? "" : "red";
  }
}

Live copy

实时复制