为什么我的功能不会在onclick上运行?

时间:2017-02-08 19:08:13

标签: javascript jquery

所以我在Javascript中制作苏打水机。 我需要跟踪每种类型苏打水的现有数量,以及总计现有多少钱,并作为信用额插入。它也需要能够做出改变。

我写了大部分内容,但我的按钮似乎没有连接。它就像从html到js的完全脱节。

这是我项目的一个方面:     的jsfiddle

我认为问题在于我可能会过度思考这个问题。只需要第二眼。

1 个答案:

答案 0 :(得分:0)

您的代码存在许多问题,从您的JSFiddle配置开始,继续讨论如何正确声明或调用您的函数:

你有:

function(addNickel){
    var availableCredit = availableCredit + 0.05;
}

 onclick="function(addNickel)"

这两个都是将函数名称放在括号中而不是之前。代码应该是:

function addNickel(){
    var availableCredit = availableCredit + 0.05;
}

 onclick="addNickel()"

您的所有函数声明和调用都是这样的,需要更新。

并且,在需要prompt时需要使用alert进行数学但不将答案存储在任何地方时,不应该使用分号错误。引导冗余代码的gob和gobs。您不需要数学函数来更新库存总量或每个苏打水的库存量。只需创建一个函数并传入数学可以使用的参数。一般的经验法则是“隔离什么不是从什么变化”。您的算法不会从苏打水变为苏打水,只有金额可以改变。

这仍然需要一点清理,但这是一个工作版本,删除了冗余代码并清除了语法:

$(function(){

  var sodaTotals = [10, 10, 10, 10];

  var cashOnHand = 40;
  var currentCredit = 0;

  var rootBeerTotal = document.getElementById('root_beer_instock');
  var pepsiTotal = document.getElementById('pepsi_instock');
  var orangeTotal = document.getElementById('orange_instock');
  var mtDewTotal = document.getElementById('mt_dew_instock');

  // Put HTML elements into an array that maps to the sodaTotals array
  var stock = [rootBeerTotal, pepsiTotal, orangeTotal, mtDewTotal];

  var machineFunds = document.getElementById('funds');
  var availableCredit = document.getElementById('available_credit');

  // Get Button references:
  var $btnNickel = $("#nickel");      
  var $btnDime = $("#dime");         
  var $btnQuarter = $("#quarter");         
  var $btnDollar = $("#1_dollar");           
  var $btn5Dollar = $("#5_dollar");

  var $btnRB = $("#root_beer");
  var $btnPep = $("#pepsi");
  var $btnOr = $("#orange");
  var $btnDew = $("#mt_dew");

  var $btnReload = $("#reload_soda");
  var $btnReset = $("#reset_COH");

  // Wire up event handlers for buttons. Each handler will call the single math function
  // but pass it the correct amount to modify the amount by
  $btnNickel.on("click", function(){ adjustPrice(.05); });
  $btnDime.on("click", function(){ adjustPrice(.1); });
  $btnQuarter.on("click", function(){ adjustPrice(.25); });
  $btnDollar.on("click", function(){ adjustPrice(1); });
  $btn5Dollar.on("click", function(){ adjustPrice(5); });

  // Array indexes start from 0, not 1
  $btnRB.on("click", function(){ dispenseSoda(0); });
  $btnPep.on("click", function(){ dispenseSoda(1); });
  $btnOr.on("click", function(){ dispenseSoda(2); });
  $btnDew.on("click", function(){ dispenseSoda(3); });
  
  $btnReload.on("click", reloadSoda);
  $btnReset.on("click", resetCOH);

  // Money stuff
  //Don't declare the variables in the functions because that will wipe out the old values
  var credit = null;
  
  // You don't need a function for each transaction, just pass the value that needs to be adjusted
  function adjustPrice(amount){
    credit += amount;
    availableCredit.textContent = credit.toFixed(2);
    machineFunds.textContent = credit.toFixed(2);
  }

  // Reset tools
  function reloadSoda(){
      sodaTotals = [10, 10, 10, 10];
  }

  function resetCOH(){
      cashOnHand = 40;
      alert("You reach into the machine and pull out what appears to be Monopoly money. Make it rain!");
  }

  // Each function represents a different flavor represented as 'dispenseFlavor'
  function dispenseSoda(flavorIndex){

    if (credit >= 0.5) {
    
      // Deduct stock amount
      sodaTotals[flavorIndex]--;
      stock[flavorIndex].textContent = sodaTotals[flavorIndex];

      // Deduct funds
      credit -= 0.50;
      document.getElementById('available_credit').textContent = credit.toFixed(2);
      
      // Add to machine's balance  
      cashOnHand += 0.50;

      alert('Please pickup your soda from below. Thank you for your purchase!');

      // Check if user has any additional money in machine
      if(credit > 0){ 

        if (confirm("Would you like to make another purchase?")) {
             alert("Please select another soda.");
        } else {
             alert('Please collect your refund below.');
             document.getElementById("refund_tray").innerHTML = credit;
             var availableCredit = 0;
        }

      } else {
        alert('Insuficient funds, please add additional funds.');
      }
    }
  }

 });
.site-title {
     font-size: 3rem;
     font-color: rgb(200, 200, 200);
 }
 
 .current-levels { width: 20%; }
 
 .payment-container {
     width: 75%;
     border: solid black 2px;
 }
 
 .payment {
     display: flex;
     flex-direction: row;
     justify-content: space-around;
 }
 
 .payment-container p { text-align: center; }
 
 .button-region-container { border: solid black 2px; }
 
 .button-container button {
     height: 5rem;
     width: 12%;
     background-size: contain;
     background-repeat: no-repeat;
 }
 
 button#root_beer { background-image: url('http://full.nick2go.com/img/root-beer.jpg'); }
 button#pepsi { background-image: url('http://full.nick2go.com/img/pepsi.jpg'); }
 button#orange { background-image: url('http://full.nick2go.com/img/orange.jpg');  }
 button#mt_dew { background-image: url('http://full.nick2go.com/img/mt-dew.jpg'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="site-title">
        <h2>Gasia's Soda Machine</h2>
    </div>
    <div class="payment-container">
    <div class="credit-container">
        <p>Funds in the Machine: <span id="funds"></span></p>
        <p>Available Credit: <span id="available_credit"></span></p>
        <p>Refund Tray:<span id="refund_tray"></span></p>
        <p>Click the below buttons to insert money into the machine:</p>
        <div class="payment">
            <button type="button" id="nickel">$0.05</button>
            <button type="button" id="dime">$0.10</button>
            <button type="button" id="quarter">$0.25</button>
            <button type="button" id="1_dollar">$1.00</button>
            <button type="button" id="5_dollar">$5.00</button>
        </div>
    </div>
    <div class="button-region-container col-xs-12">
        <p class="button-title">Select a soda from below:</p>
        <div class="button-container">
            <button id="root_beer" alt="root beer"></button>
            <button id="pepsi" alt="pepsi can"></button>
            <button id="orange" alt="orange can"></button>
            <button id="mt_dew" alt="mt-dew can"></button>
        </div>
    </div>
    <div class="current-levels .col-xs-6">
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="root_beer_title">Number of cans of Root Beer remaining:<span id="root_beer_instock">10</span></p>
        </div>
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="pepsi_title">Number of cans of Pepsi remaining:<span id="pepsi_instock">10</span></p>
        </div>
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="orange_title">Number of cans of Orange remaining:<span id="orange_instock">10</span></p>
        </div>
        <div class="flex-soda-total" id="rootbeer_stats">
            <p id="mt_dew_title">Number of cans of Mt. Dew remaining:<span id="mt_dew_instock">10</span></p>
        </div>
    </div>
    <div class="admin-tools">
        <p>The button on the left will reset the soda stock, back to default levels. The button on the right will withdraw all the money from the machine. Choose wisely.</p>
        <button id="reload_soda">Refill Soda Machine</button>
        <button id="reset_COH">Rob The Machine!</button>
    </div>