首页 > 解决方案 > 我被困在获取 HTML 按钮以开始 JS 脚本

问题描述

在我的最后一个问题之后,我尝试使用 JS 文件,但它无法与单击 HTML 按钮开始 JS 文件中的功能一起工作;在 JS 脚本要钱和苏打水产品的代码后,我无法通过单击 HTML 页面中的“BEGIN”再次重新启动该功能。

我该如何解决这个问题?

*我想挑战自己编写 Javascript 函数而不使用 HTML 中的函数。

*因为我住在澳大利亚,所以我使用澳元面额。

var beginMachine = document.getElementById("beginMachine");
beginMachine.addEventListener("click", vendingFunction);

function vendingFunction() {
  var $money = 0;
  var codeSequence = ["A1", "A2", "B1", "B2"];
  var $soda = ["Coca-Cola", "Fanta", "Sprite", "Schweppes"];
  const coinValue = {'0.20': 0.20, '0.50': 0.50, '1.00': 1.00, '2.00': 2.00};
  const sodaPrice = [1.55, 2.95, 1.85, 3.90];
  const formatMoney = new Intl.NumberFormat('en-AU', {style: 'currency', currency: 'AUD'}).format; //Change the currency format to AUD for clarity in currency used.

  return {
      insertCoin: () => { //The arrow function '=>' acts a simple indicator to call a function
          var coin = window.prompt("Insert any coin. (20c, 50c, $1, $2)");
          $money += coinValue[coin] || 0;
          if (typeof coinValue[coin] === 'undefined') alert('Invalid Choice'); //'undefined' means no value or invalid value
          console.log('You now have ' + formatMoney($money));
      },
      selectItem: () => {
          var sodaChoice = window.prompt("Select your code.");
          console.log(sodaChoice);

          if (sodaChoice == "A1") {
            window.alert("You selected Coca-Cola.");
            window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
            window.alert(sodaPrice[0] <= $money ? "You have enough." : "You don't have enough.");
          }

          if (sodaChoice == "A2") {
            window.alert("You selected Fanta.");
            window.alert("This costs $" + sodaPrice[1] + ".");
            window.alert(sodaPrice[1] <= $money ? "You have enough." : "You don't have enough.");
          }

          if (sodaChoice == "B1") {
            window.alert("You selected Sprite.");
            window.alert("This costs $" + sodaPrice[2] + ".");
            window.alert(sodaPrice[2] <= $money ? "You have enough." : "You don't have enough.");
          }

          if (sodaChoice == "B2") {
            window.alert("You selected Schweppes");
            window.alert("This costs $" + sodaPrice[3] + ".");
            window.alert(sodaPrice[3] <= $money ? "You have enough." : "You don't have enough.");
          }
      }
  }
}

const app = vendingFunction();
for (let i = 0; i < 5; i++) {
  app.insertCoin();
}
app.selectItem();
//Code from dave in StackOverflow <https://stackoverflow.com/questions/67929579/how-do-you-program-this-javascript-file-for-allowing-more-than-one-denominations/67929809
//See <https://www.youtube.com/watch?v=qsEtXR38IQ8&ab_channel=EnvatoTuts%2B>
body {background-color: lightgrey;}

.vendingMachine
{
    position:static;
    top: 0;
    left: 0;
    z-index: 1;
}

.mainFont 
{
    font-family: Arial, sans-serif;
    font: 12px/14px;
}
<!DOCTYPE html>
<html> <!-- Tells this document is coded in HTML5 -->
<head>
<link rel="stylesheet" href="0az_style.css"><!-- Links to the CSS file that handles the layout and design of the webiste, specifically the buttons' and vending machine's positions. -->
    <title>Vending Machine</title> <!-- Names the browser tab -->
</head>


<!--Calls the mainFont variable in the CSS file to change every letter into Arial-->
<body class="mainFont"><!--Changes every letter to a specific font-->

    <!--Creates a large heading like Heading 1 in Word-->
    <h1>Welcome to the Vending Machine</h1>

    <!--<div> generically stores CSS code but for these lines, Javascript is called upon to activate the remaining scripts-->
    <div> 
        <img    class="fit-picture" 
                src="Vending-Machine-alt.png"
                width="1255"
                height="1835"
                alt="Picture of a vending machine.">
    </div>
    <br>






    <!-- From https://stackoverflow.com/questions/9530954/how-to-call-external-javascript-function-in-html -->
    <!-- Adding <script type="text/javascript"></script> calls this function right away. Perhaps use inline JS to tell the button to load JS script after the page loads.-->
    <button id="beginMachine">BEGIN</button>




    <br>
<!--<a href= '0az_how_to_use.html'> links to the manual page in this project's main folder-->
<h2><a href= '0az_how_to_use.html'>How to use the vending machine</a></h2>
</body>
</html>

标签: javascripthtml

解决方案


您的vendingFunction()函数返回一个带有函数的对象,它不执行它们。您需要另一个可以执行它们的函数:

var beginMachine = document.getElementById("beginMachine");
beginMachine.addEventListener("click", start);

function vendingFunction() {

  var $money = 0;
  var codeSequence = ["A1", "A2", "B1", "B2"];
  var $soda = ["Coca-Cola", "Fanta", "Sprite", "Schweppes"];
  const coinValue = {'0.20': 0.20, '0.50': 0.50, '1.00': 1.00, '2.00': 2.00};
  const sodaPrice = [1.55, 2.95, 1.85, 3.90];
  const formatMoney = new Intl.NumberFormat('en-AU', {style: 'currency', currency: 'AUD'}).format; //Change the currency format to AUD for clarity in currency used.

  return {
      insertCoin: () => { //The arrow function '=>' acts a simple indicator to call a function
          var coin = window.prompt("Insert any coin. (20c, 50c, $1, $2)");
          $money += coinValue[coin] || 0;
          if (typeof coinValue[coin] === 'undefined') alert('Invalid Choice'); //'undefined' means no value or invalid value
          console.log('You now have ' + formatMoney($money));
      },
      selectItem: () => {
          var sodaChoice = window.prompt("Select your code.");
          console.log(sodaChoice);

          if (sodaChoice == "A1") {
            window.alert("You selected Coca-Cola.");
            window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
            window.alert(sodaPrice[0] <= $money ? "You have enough." : "You don't have enough.");
          }

          if (sodaChoice == "A2") {
            window.alert("You selected Fanta.");
            window.alert("This costs $" + sodaPrice[1] + ".");
            window.alert(sodaPrice[1] <= $money ? "You have enough." : "You don't have enough.");
          }

          if (sodaChoice == "B1") {
            window.alert("You selected Sprite.");
            window.alert("This costs $" + sodaPrice[2] + ".");
            window.alert(sodaPrice[2] <= $money ? "You have enough." : "You don't have enough.");
          }

          if (sodaChoice == "B2") {
            window.alert("You selected Schweppes");
            window.alert("This costs $" + sodaPrice[3] + ".");
            window.alert(sodaPrice[3] <= $money ? "You have enough." : "You don't have enough.");
          }
      }
  }
}

function start()
{
  const app = vendingFunction();
  for (let i = 0; i < 5; i++) {
    app.insertCoin();
  }
  app.selectItem();
}
start();
//Code from dave in StackOverflow <https://stackoverflow.com/questions/67929579/how-do-you-program-this-javascript-file-for-allowing-more-than-one-denominations/67929809
//See <https://www.youtube.com/watch?v=qsEtXR38IQ8&ab_channel=EnvatoTuts%2B>
body {background-color: lightgrey;}

.vendingMachine
{
    position:static;
    top: 0;
    left: 0;
    z-index: 1;
}

.mainFont 
{
    font-family: Arial, sans-serif;
    font: 12px/14px;
}
<!DOCTYPE html>
<html> <!-- Tells this document is coded in HTML5 -->
<head>
<link rel="stylesheet" href="0az_style.css"><!-- Links to the CSS file that handles the layout and design of the webiste, specifically the buttons' and vending machine's positions. -->
    <title>Vending Machine</title> <!-- Names the browser tab -->
</head>


<!--Calls the mainFont variable in the CSS file to change every letter into Arial-->
<body class="mainFont"><!--Changes every letter to a specific font-->

    <!--Creates a large heading like Heading 1 in Word-->
    <h1>Welcome to the Vending Machine</h1>

    <!--<div> generically stores CSS code but for these lines, Javascript is called upon to activate the remaining scripts-->
    <div> 
        <img    class="fit-picture" 
                src="Vending-Machine-alt.png"
                width="1255"
                height="1835"
                alt="Picture of a vending machine.">
    </div>
    <br>






    <!-- From https://stackoverflow.com/questions/9530954/how-to-call-external-javascript-function-in-html -->
    <!-- Adding <script type="text/javascript"></script> calls this function right away. Perhaps use inline JS to tell the button to load JS script after the page loads.-->
    <button id="beginMachine">BEGIN</button>




    <br>
<!--<a href= '0az_how_to_use.html'> links to the manual page in this project's main folder-->
<h2><a href= '0az_how_to_use.html'>How to use the vending machine</a></h2>
</body>
</html>


推荐阅读