1

我对 JavaScript 没有太多经验,尽管我用其他语言编程并且大致了解所有函数和事件侦听器的作用以及诸如此类的东西。

但是,我已经玩了几个小时的作业,并且不确定某些事情,我试图使用谷歌找到答案,但没有运气。

所以我试图做到这一点,以便在事件发生时调用函数(例如“模糊”和“点击”),但是似乎所有的监听器都加载到了“addListeners()”函数中。所有事件侦听器仅在页面加载/重新加载时触发,然后它们发送警报。

代码如下所示:

  <!DOCTYPE HTML>

<html>
<head>
<link rel="stylesheet" type="text/css" href="order-form.css">
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>Food order form</title>
<script type="text/Javascript">

function validateForm (form) {
    if (isNotEmpty(form.room)){  
      if (checkName(form.name)){ 

        if (validRoom(form.room)) {

          return true;
        }
      }
    }
  return false;
}

function isNotEmpty(elem){
  var str = elem.value;
  if (str == null || str.length == 0){
    alert("Please fill in the required fields.");
    return false;
  }
  else {
    return true;
  }
}

function checkName(theName) {
  if (theName.value == "") {
    alert ("Name must be entered");
    return false;
  };
  if (!validName(theName.value)){
    alert("Name should be alphabetic"); 
    return false;
  };
  return true;
}

function validName(theName) {
var valid = true;
for (var i = 0; i < theName.length; i++) {
   thisChar = theName.charAt(i);
   if ( ((thisChar < "A") || (thisChar > "Z")) &&
       ((thisChar < "a") || (thisChar > "z"))){ 
           return !valid;
       }; 
   };
theName.charAt(0).toUpperCase();
return valid;
}

function validRoom(theRoom) {
  var valid = true;
  if (theRoom.value == "") {
        alert ("Room number must be entered");
        return !valid;
  };
  roomNumber = parseInt(theRoom.value); 
  if (isNaN(roomNumber)){  
    alert("A number is required"); 
        return !valid;
  };
  if ((roomNumber < 100) || (roomNumber > 399)){
    alert("Room number must be between 100 and 399"); 
        return !valid;
  };
  return valid;
}

  function formClock() {
   var time = new Date()
   var hour = time.getHours()
   var minute = time.getMinutes()
   var second = time.getSeconds()
   var temp = "" + ((hour > 12) ? hour - 12 : hour)
   temp += ((minute < 10) ? ":0" : ":") + minute
   temp += ((second < 10) ? ":0" : ":") + second
   temp += (hour >= 12) ? " P.M." : " A.M."
   document.FoodOrder.Time.value = temp ;
   setTimeout("formClock()",1000) ;
}

  function checkRoom(theRoom) {
    if (theRoom.value ==""){
        alert("Room number must be entered");}

    roomNumber = parseInt(theRoom.value);
    if (isNaN(roomNumber)){
            alert("A number is required");}

    if ((roomNumber < 100) || (roomNumber > 399)){
            alert("Room number must be between 100 and 399"); 
      } 
}

  function addListeners(){
  clock = document.getElementById("clock");
  clock.addEventListener("mouseover", formClock, false);

  submit = document.getElementById("submit");
  submit.addEventListener("click", validateForm(FoodOrder), false);

  room = document.getElementById("room");
  room.addEventListener("blur", checkRoom(FoodOrder.room), false);
    }



  window.addEventListener("load", addListeners, false);
</script>
</head>

<body>
<h2>Froggle's Food Delivery Service<br>Order Form</h2>

<div class="form"><form NAME="FoodOrder"
      ACTION="#"
      METHOD="POST">

<p><input TYPE = "text" NAME = "Time" id="clock" SIZE = 20>
<p>Name <input TYPE = "text" NAME = "name" SIZE = 20>

<br>IST Room <input TYPE = "text" NAME = "room" id="room" SIZE =3>

<br>Food Menu: 
   <br> <input TYPE="radio" NAME="food" value="Chilli-4.50">Chilli $4.50
  <br><input TYPE="radio" NAME="food" value="Pizza-2.50"> Pizza  $2.50
  <br><input TYPE="radio" NAME="food" value="Wedges-4.50"> Wedges $4.50
  <br><input TYPE="radio" NAME="food" value="Bagel-3.00"> Bagel $3.00
<br><br>Drink Menu: 
    <br><input TYPE="radio" NAME="drink" value="Flavoured Milk-1.00"> Flavoured $1.00
    <br><input TYPE="radio" NAME="drink" value="Mineral Water-1.50"> Mineral Water  $1.50
    <br><input TYPE="radio" NAME="drink" value="Ale-4.50"> Ale $4.50

<br>
<br>  <input TYPE=SUBMIT VALUE="Order" id="submit" >
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input TYPE=RESET VALUE="Cancel"><br>
</form></div>

  </body>
  </html>

提前感谢任何和所有帮助。

4

2 回答 2

2

问题在于这些代码行:

  submit = document.getElementById("submit");
  submit.addEventListener("click", validateForm(FoodOrder), false);

  room = document.getElementById("room");
  room.addEventListener("blur", checkRoom(FoodOrder.room), false);

validateForm(FoodOrder)立即checkRoom(FoodOrder.room)执行这些功能。只要你有一个函数名后跟,你就是在向 Javascript 发送一个命令来立即执行这个函数。然后将该函数的结果指定为事件侦听器。显然,这会计算页面加载的结果和时间,并且随后不会做任何有用的事情。()validateFormcheckForm

当然,您想要做的是仅在触发事件时执行这些代码片段。为此,您需要将实际函数传递给addEventListener,就像在以下代码行中所做的那样:

clock.addEventListener("mouseover", formClock, false);

但是您需要将参数传递给函数,而仅通过传递名称是无法做到的。那么该怎么办?好吧,您实际上需要创建另一个函数,该函数在事件触发时运行,然后使用适当的参数调用您想要的函数:

  submit = document.getElementById("submit");
  submit.addEventListener("click", function() {
      validateForm(FoodOrder);
  }, false);

  room = document.getElementById("room");
  room.addEventListener("blur", function() {
      checkRoom(FoodOrder.room);
  }, false);

您可以在 jsFiddle 上查看您的代码,这是一个用于测试和原型化 Javascript 和 HTML 的好工具!

还要注意一点你的代码是不好的做法:

setTimeout("formClock()",1000) ;

将字符串传递给setTimeout. 您可以传递一个函数对象:

setTimeout(formClock, 1000);
于 2013-11-06T08:08:20.430 回答
1

这是因为你正在调用你的函数

validateForm(FoodOrder)

立即将他们的结果分配给事件

如果上面的函数返回另一个函数会很好,但事实并非如此

所以只需将它包装在另一个函数中,如下所示:

submit.addEventListener("click", function() { validateForm(FoodOrder) }, false);

您还应该将loadevent替换为DOMContentLoaded以更早地附加您的事件

但最好使用jQuery

$(function() {
    $('#clock').mouseover(formClock);
    $('#submit').click(function() { validateForm(FoodOrder) });
    $('#room').blur(function() { checkRoom(FoodOrder.room) });
}
于 2013-11-06T08:10:22.807 回答