我正在练习事件听众和功能,并且正在尝试构建一个非常简单的纸牌游戏。单击相应的按钮后,我的前2个函数可以获取卡1和2的值。我已经构建了第三个来组合总数,但是无法将生成的值拉到第三个函数中。我的第三个函数总是返回零。我明白了,但是还没有找到解决方案从前两个函数中提取值。感谢任何帮助。谢谢。
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;
}
答案 0 :(得分:1)
您正在将card1Value
,card2Value
和totalCardsValue
重新声明为本地范围。移除前面的var
。这样做,您不需要从generateCard()
和generateCard()
函数返回任何值,因为您正在使用全局变量。
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;
}