在执行功能中停止功能

时间:2017-06-12 02:11:31

标签: javascript

    <script type="text/javascript">
    var counter = 0;
            document.onkeypress = function(evt) {
        evt = event || window.event;
        var charCode = evt.keyCode || evt.which;
        var charStr = String.fromCharCode(charCode);
        document.getElementById("demo").innerHTML = charStr;
            if(charStr) {
                counter = counter + 1;
                document.getElementById("counter").innerHTML = counter;
            }
                if(counter == 100) {
                    alert("You reached the limit");
                    return;
        }

    };

    </script>

我想在计数器达到100时这样做,我的网站发出警报说我达到了极限并停止执行该功能。换句话说,如果我点击另一个键,则没有任何实际发生。

1 个答案:

答案 0 :(得分:-2)

if (!counter) var counter = 0;

    document.onkeypress = function(evt) {
    if(counter == 100) {
                alert("You reached the limit");
                return;
    }
    evt = event || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    document.getElementById("demo").innerHTML = charStr;
        if(charStr) {
            counter = counter + 1;
            document.getElementById("counter").innerHTML = counter;
        }

};