2015-11-08 72 views
-1

我正在練習事件監聽器和函數,並試圖構建一個非常簡單的紙牌遊戲。我的第一個2個函數用於在單擊相應按鈕後獲取卡片1和卡片2的值。我已經構建了三分之一來組合總數,但無法將生成的值拉到第三個函數中。我的第三個函數總是返回零。我明白爲什麼,但一直未能找到解決方案來從前兩個函數中獲取值。任何幫助表示讚賞,謝謝。來自多個函數的javascript拉值

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

你是怎麼調用'generateCard *'的?你對返回值做什麼?你必須將它們分配給... –

+0

再次感謝此工作。我沒有使用我猜的回報。 – KM617

回答

1

您要重新聲明你card1Valuecard2ValuetotalCardsValue到本地範圍。在他們面前刪除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; 
    } 
+0

這很有道理。謝謝! – KM617