<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时这样做,我的网站发出警报说我达到了极限并停止执行该功能。换句话说,如果我点击另一个键,则没有任何实际发生。
答案 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;
}
};