为什么我的javascript函数不能运行?

时间:2017-11-14 16:14:17

标签: javascript html

我试图创建一个登录页面,在将数据提交到处理它的php页面之前验证数据。我使用javascript进行验证。这是我的代码:

 <div class = mainInfo>
    <?php include "header.php"; ?>        
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>
    <div id="feedback"> 
    </div>
 </div>
<script>  
function validate()
{
    document.getElementById("feedback").innerHTML = "functionbeingcalled";
    var p1 = document.getElementById("p1").value,
                p2 = document.getElementById("p2").value);
    if( ! p1===p2 )
    {

        document.getElementById("feedback").innerHTML = "passwords dont match";
    }
    if(p1==="")
    {
         document.getElementById("feedback").innerHTML = "Must have a password";
    }
}
window.setInterval(validate(),1000);
</script>

<?php include "footer.php"; ?>

我会认为这个脚本应该从页面加载的每一秒开始运行,但脚本根本不运行。这一行:

 document.getElementById("feedback").innerHTML = "functionbeingcalled";

也没有工作。

除了这个问题之外,是否可以在使用php提交之前验证数据?我是网络编程的新手。

3 个答案:

答案 0 :(得分:0)

传递函数而不是调用它。

//             no parentheses!
window.setInterval(validate, 1000);

这是错误的。

if( ! p1===p2 )

应该是这个

if( p1!==p2 )

因为前缀!

的优先级较高

答案 1 :(得分:0)

我建议您在输入字段中添加侦听器! ;)

  1. 然后,只有在进行更改时才会运行验证代码。换一种说法;只在必要的时候。
  2. 它将立即运行验证码&#34;&#34;当输入改变时。而不是每1000毫秒验证一次。
  3. 我看到你还没有使用jQuery(还)?如果您想验证&#39;更改&#39;使用普通的js,这是一个解决方案:Plain js solution

    如果您可以将jQuery库添加到代码中,那么可以像jQuery solution

    那样轻松完成

答案 2 :(得分:0)

嗯,你有几个问题......

首先,使用 setInterval() ,您只传递对应该调用的函数的引用(在您的情况下为validate),您实际上并未调用就像你在做的那样(validate())。这基本上立即运行validate,然后将返回值设置为每秒调用的函数。由于validate()没有返回值,因此此后每秒都不会发生任何事情。

您还有一个拼写错误:if( ! p1===p2 ),表示正在针对p1测试与p2相反的布尔值。你想要的是:if(p1 !== p2 ),这就是你表达的方式,而不是严格等于&#34;。

现在,你真的要以错误的方式进行验证。而不是在计时器上运行验证功能,这是效率低下的,你想要在其中一个或多个中验证案例:

  • 就在整个表单提交之前
  • 在用户离开表单字段
  • 之后
  • 用户输入数据
  • 所有3
  • 的某种组合

每个场景都是通过事件处理程序处理的,每个场景的工作示例如下所示。

&#13;
&#13;
// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");

// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");

var form = document.querySelector("form");

// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){ 
  // If validate function returns false, don't submit
  if(!validate()){
    evt.preventDefault(); // cancel the form submission
    feedback.textContent = "Can't submit. Form is not valid!";
  }
});

// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");

// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);

// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
  input.addEventListener("blur", validate);   // Used to validate when user moves off of each element
  input.addEventListener("input", validate);  // Used to validate as data is being entered
});


function validate()  {
  // Keep track of whether the form is valid or not. Assume that it is by default
  var valid = true;

  // .innerHTML is for when you want to assign a string containing
  // HTML to a DOM element. This invokes the HTML parser and renders
  // the HTML. If you don't have HTML in the string, use .textContent
  // instead, which doesn't invoke the HTML parser and is more efficient
  
  // See if the password was typed in both boxes before telling the user 
  // that the passwords don't match
  if(p1.value && p2.value){
    // Are they the same?
    if(p1.value !== p2.value){
      feedback.textContent = "passwords dont match";
      valid = false;
    } else {
      feedback.textContent = "passwords match";
    }
  } else {
    // If both password fields aren't filled in, the form can't be valid
    valid = false;
  }
  
  if(p1.value === "") {
   feedback.textContent = "Must have a password";
   valid = false;
  }
  
  // Send a result to the caller so it can be known by other code if the form is valid
  return valid;
}
&#13;
<div class = "mainInfo">
  <form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
    <div>username: <input type="text" name="userName"></div>
    <div>password: <input id="p1" type="password" name="password"></div>
    <div>reenter password:  <input id="p2" type="password" name="passwordConfirmation"></div>

    <!-- Any form element that has a "name" attribute will submit its name/value as
         part of the form data when the form gets submitted. You probably don't want
         the actual submit button to be included in this, so don't give the button
         a "name" attribute. -->
    <input type="submit" value="submit">     <input type="reset" value="reset">
  </form>
  <div id="feedback"></div>
</div>
&#13;
&#13;
&#13;