2011-12-05 62 views
0

我有一些我試圖在HTML頁面上實現的javacript。代碼如下 - 如何在打開.html文件後立即運行它?它希望它在我打開它時立即提示我輸入重量。JavaScript:沒有在頁面上運行

<script type="text/javascript"> 
    var weight = parseInt(prompt("What is your weight?")); 
    if (weight > 126) { 
     alert('Please enter a weight lighter than 126'); 
    } 
    document.writeln('<br/>'); 
    var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"]; 

    function recruit() { 
     if (0 < weight < 112){ 
      document.writeln('You are in' + wArray[0] +'class!'); 
     } 
     if (112 < weight < 115){ 
      alert('You are in' + wArray[1] +'class!'); 
     } 
     if (weight > 115 && weight < 118){ 
      alert('You are in' + wArray[2] +'class!'); 
     } 
     if(weight > 118 && weight < 122){ 
      alert('You are in' + wArray[3] +'class!'); 
     } 
     if (weight > 122&& weight < 126){ 
      alert('Your weight class is' + wArray[4]); 
    } 
</script> 
+0

只需要注意,你應該在''parseInt'中添加',10'。像這樣:'parseInt(提示(「你的體重是多少?」),10)'。 –

回答

1

你有2個問題的腳本:

  • recruit()缺少右括號}
  • 你是任何地方都不要撥打recruit()

其他幾個問題:):

  • 112 < weight < 115是不是你想要的。

    var weight = 1000; 
    // 112 < 1000 => true, true < 115 => true 
    if (112 < weight < 115) { 
        alert("112 < weight < 115"); 
    } 
    
    • 你離開:即使重1000將檢查權重比112大,然後比較,如果結果小於115

    嘗試將返回true您的支票中有一些值。如果您在另一個if中檢查一個ifweight > 118中的weight < 118,那麼如果重量恰好爲118,會發生什麼情況?

  • 使用if { } else if { }塊而不是多個if-s。在您的招聘功能中,即使重量爲110,並且第一個if塊的主體被執行,您仍然在檢查每個其他if的重量。

  • 向輸出字符串添加空格,例如:'You are in ' + wArray[0] + ' class! :)。

  • 由於火箭在評論中寫道:parseInt()應該10作爲第二個參數(基數)來強制解析成十進制系統調用。見this

  • Bonus:請儘快停止使用document.writeln,因爲它會教你不良做法。例如參見thisthis

HERE是一個版本解決這些問題。

注:的代碼裏面window.onload執行,以確保該文檔的其餘部分已經被加載,所以他可以訪問div

0
<script type="text/javascript"> 
    var weight = parseInt(prompt("What is your weight?")); 
    if (weight > 126) { 
    alert('Please enter a weight lighter than 126'); 
    } 
    document.writeln('<br/>'); 
    var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"]; 


    function recruit() { 
    if (0 < weight < 112){ 
     document.writeln('You are in' + wArray[0] +'class!'); 
    } 
    if (112 < weight < 115){ 
     alert('You are in' + wArray[1] +'class!'); 
    } 
    if (weight > 115 && weight < 118) { 
     alert('You are in' + wArray[2] +'class!'); 
    } 
    if(weight > 118 && weight < 122){ 
     alert('You are in' + wArray[3] +'class!'); 
    } 
    if (weight > 122&& weight < 126){ 
     alert('Your weight class is' + wArray[4]); 
    } 
    } 
    recruit(); 
</script> 
+2

有點解釋會有幫助,我不認爲你需要重新發布代碼,除非你改變它。如果確實如此,請突出顯示更改內容。 –

+0

你忘了「}」,你必須調用招聘功能:) –

0

你可以調用javascript函數加載網頁時是這樣的:

<body onload="myFunction();"> 
相關問題