关闭函数问题javascript

时间:2015-09-17 22:25:50

标签: javascript

我的随机数正常,但我的计数器没有。我的计数器应该在每次单击按钮时添加一个,而只是显示1为什么不呢?我没有得到任何控制台错误。我不知道问题是什么。我想要使​​用闭包函数。我相信我正确地做了。

HTML

<div>
    <button type="button" onclick="showNumber()">Number</button>
    <p id="counter"></p>
    <p id="ran_num"></p>
</div>

的javascript

function showNumber() {
    var number1 = 0;
    var counter1 = 0;

    var randomNum = (function() {
        return function() {
        return number1 = Math.floor((Math.random() * 100) + 1);}
    })();

    var counterNum = (function() {
        return function() {
        return counter1 += 1}
    })();

    document.getElementById("counter").innerHTML = "Count = " + counterNum();
    document.getElementById("ran_num").innerHTML = "Random Number = " + randomNum();
}

2 个答案:

答案 0 :(得分:4)

如果您希望counter1showNumber的调用之间保持其状态,则不应在其中定义它。相反,尝试这样的事情:

(function() { // this is your closure
    var counter = 0;
    function randomNum() {
        return Math.floor(Math.random()*100) + 1;
    }
    function counterNum() {
        counter++;
        return counter;
    }

    function showNumber() {
        document.getElementById('counter').innerHTML = "Count = " + counterNum();
        document.getElementById('ran_num').innerHTML = "Random Number = " + randomNum();
    }

    // make showNumber accessible in the global scope:
    window.showNumber = showNumber;
})();

答案 1 :(得分:0)

使用大部分现有代码

function showNumber() {

    var randomNum = function() {
        return Math.floor((Math.random() * 100) + 1);
    }

    var counterNum = (function() {
        var counter = 0;
        return function() {
            return ++counter;
        }
    })();

    document.getElementById("counter").innerHTML = "Count = " + counterNum();
    document.getElementById("ran_num").innerHTML = "Random Number = " + randomNum();
}