2011-03-09 22 views
1

我正在嘗試製作一個表單,其中包含一個用戶名,然後當提交按鈕被按下時,會顯示一個提示,說明早上,下午或晚上(取決於時間) 。我覺得我在吐痰距離我,但我只是無法得到它的工作,這裏是代碼的相關片段:涉及表單和提醒的簡單JavaScript問題

<script type="text/javascript"> 
<!-- 
    function say_hello() { 
     var date = new Date(); 
     var time = date.getHours(); 
     var name = document.forms["hello"]["name"].value; 

      if (time < 12) { 
       alert ("Good morning, "+name+"!"); 
      } 

      else if (time > 12 && time < 18) { 
       alert ("Good afternoon, "+name+"!") 
      } 

      else { 
       alert ("Good evening, "+name+"!") 
      } 
     ); 
    } 
// --> 
</script> 

和HTML:

<form name="hello" action=""> 
    <p> 
    What is your name? 
    <input type="text" name="name" size="10"> 
    </input> 
    </p> 
    <p> 
    <input type="button" name="Submit" onclick="say_hello()" value="Receive Personal Message!"> 
    </input> 
    </p> 
</form> 

謝謝! :D

+0

你將不得不'event.preventDefault() '這樣表格實際上不會被提交。另外,什麼是不工作? – JCOC611 2011-03-09 00:55:22

+0

當我按下按鈕什麼都沒有發生。 – 2011-03-09 00:58:06

回答

0
function say_hello() { 
    var date = new Date(); 
    var time = date.getHours(); 
    var name = document.forms["hello"]["name"].value; 

     if (time < 12) { 
      alert ("Good morning, "+name+"!"); 
     } 

     else if (time > 12 && time < 18) { 
      alert ("Good afternoon, "+name+"!") 
     } 

     else { 
      alert ("Good evening, "+name+"!") 
     } 
    //); //This causes a syntax error 
} 
+0

謝謝。現在看起來非常明顯!因爲它是第一個打勾你的。希望這一切都OK :) – 2011-03-09 01:08:22

0

您在JavaScript中有語法錯誤。該「);」是不必要的。

function say_hello() { 
    var date = new Date(); 
    var time = date.getHours(); 
    var name = document.forms["hello"]["name"].value; 

    if (time < 12) { 
     alert ("Good morning, "+name+"!"); 
    } 

    else if (time > 12 && time < 18) { 
     alert ("Good afternoon, "+name+"!"); 
    } 

    else { 
     alert ("Good evening, "+name+"!") 
    } 
} 
+0

是真的,但它仍然不起作用。 – amosrivera 2011-03-09 00:58:22

+0

謝謝。現在看起來非常明顯! – 2011-03-09 01:04:42

0

在你的功能,有一個語法錯誤剛剛過去else {...}後,有一個不必要的);

嘗試刪除它,它應該工作!

+0

謝謝。現在看起來非常明顯! – 2011-03-09 01:03:54

0

修復所有的語法錯誤,我建議你連接這樣的事件:

document.forms["hello"]["Submit"].onclick=say_hello; 

相反onclick="..."

LIVE DEMO