简体   繁体   中英

javascript pull values from multiple functions

I'm practicing with event listeners and functions and am trying to build a very simple card game. My first 2 functions work to get values of card 1 and 2 once the respective buttons are clicked. I've built a third to combine the total, but having trouble pulling the generated values into a third function. My third function always returns zero. I get why, but haven't been able to find a solution to pull the values from the first 2 functions. Any help is appreciated, thanks.

var cardButton = document.getElementById('cardButton1');
  var cardButton2 = document.getElementById('cardButton2');
  var cardValue = document.getElementById('cardValue');
  var cardValue2 = document.getElementById('cardValue2');
  var cardTotalButton = document.getElementById('cardTotalButton');
  var cardTotal = document.getElementById('displayTotal');
  var card1Value = 0;
  var card2Value = 0;
  var totalCardsValue = 0;
  var cardMin = 1;
  var cardMax = 14;


  function generateCard(){
    var card1Value = randCard();
    cardValue.innerHTML = 'card value is ' + card1Value;
    return card1Value;
  }

  function generateCard2(){
    var card2Value = randCard();
    cardValue2.innerHTML = 'card value is ' + card2Value;
    return card2Value;
  }

  function getPlayerTotal(){
    var totalCardsValue = card1Value + card2Value;
    //console.log(cardValue2 + 'test');
    cardTotal.innerHTML = 'card total is ' + totalCardsValue;

  }

cardButton.addEventListener('click',generateCard);
cardButton2.addEventListener('click',generateCard2);
cardTotalButton.addEventListener('click',getPlayerTotal);



function randCard(){
  var genRandCard = Math.floor(Math.random()*cardMax)+1;
  return genRandCard;
}

You are re-declaring your card1Value , card2Value , and totalCardsValue to a local scope. Remove the var in front of them. Doing it this way, you don't need to return any value from the generateCard() and generateCard() function because you're using the global variables.

  function generateCard(){
    card1Value = randCard(); //<-------Don't use var here
    cardValue.innerHTML = 'card value is ' + card1Value;
    return card1Value; //<-------This line is not really needed
  }

  function generateCard2(){
    card2Value = randCard(); //<-------Don't use var here
    cardValue2.innerHTML = 'card value is ' + card2Value;
    return card2Value; //<-------This line is not really needed
  }

  function getPlayerTotal(){
    totalCardsValue = card1Value + card2Value;  //<-------Don't use var here
    //console.log(cardValue2 + 'test');
    cardTotal.innerHTML = 'card total is ' + totalCardsValue;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM