簡體   English   中英

我的JS中有一個簡單的邏輯錯誤,我不知道該怎么找到

[英]There's a simple logic error in my JS that I lack the knowledge to find

 <!DOCTYPE html> <html> <head> <title> Unit 2 Graded Exercise 1 </title> </head> <body> <header> <h1>Unit 2 Graded Exercise 1</h1> <br/> </header> <form> <fieldset> <label for="price" id="label">Purchase Price</label> <input type="text" id="partPrice" /> <button type="button" id="button">Calculate Shipping and Handling</button> </fieldset> </form> </body> <script> var partPrice = document.getElementById("partPrice").value; var totalPrice; function calcTotal() { if (partPrice <= 25) { var totalPrice = partPrice + 1.5; //price + sh } else if (partPrice > 25) { var totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price } alert("Shipping and Handling is $" + totalPrice); } var submitButton = document.getElementById("button"); if (submitButton.addEventListener) { submitButton.addEventListener("click", calcTotal, false); } else if (submitButton.attachEvent) { submitButton.attachEvent("onclick", calcTotal); } </script> </html> 

因此,我的目標是在總費用低於或等於25美元時顯示利息+ 1.50美元,而在25美元以上的總費用中顯示10%的利息。 我的問題是沒有收到用戶輸入的價格“ partPrice”。 我已經對此進行了很多研究,並且看到人們通過創建多個變量來拾取某些值來解決問題,但是我還不明白為什么。 我真的很想要一個解釋,因為在這段代碼中,從邏輯上講它們看起來都是正確的。 我真的不知道該在哪里更改語法。

更新您的代碼以關注

  • 將獲取值代碼移到函數內部
  • 將字符串值轉換為數字

      function calcTotal() { var partPrice = parseFloat(document.getElementById("partPrice").value); ... } 

只是在函數內部獲取數據。 還刪除if語句中的變量聲明

 <html> <head> <title> Unit 2 Graded Exercise 1 </title> </head> <body> <header> <h1>Unit 2 Graded Exercise 1</h1> <br/> </header> <form> <fieldset> <label for="price" id="label">Purchase Price</label> <input type="text" id="partPrice" /> <button type="button" id="button">Calculate Shipping and Handling</button> </fieldset> </form> </body> <script> var partPrice, totalPrice; function calcTotal() { partPrice = document.getElementById("partPrice").value; if (partPrice <= 25) { totalPrice = partPrice + 1.5; //price + sh } else if (partPrice > 25) { totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price } alert("Shipping and Handling is $" + totalPrice); } var submitButton = document.getElementById("button"); if (submitButton.addEventListener) { submitButton.addEventListener("click", calcTotal, false); } else if (submitButton.attachEvent) { submitButton.attachEvent("onclick", calcTotal); } </script> </html> 

var partPrice = document.getElementById("partPrice").value;

加載腳本后,該行執行一次,因此partPrice將為空字符串。 它,當你在寫什么輸入無法自動重新計算,所以你必須調用document.getElementById("partPrice").value再次calcTotal獲取的當前值partPrice

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM