计算按下按钮的次数 [英] counting the number of times a button is pressed
本文介绍了计算按下按钮的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须创建一个按钮,每次单击它都会向计数器添加一个.SO计数器将如下所示.计数器:0,然后单击按钮,计数器将变为1,依此类推.到目前为止,它只上升到第一位.
I have to make a button that everytime it is clicked it adds one to the counter. SO counter would look like this. Counter: 0 and then once the button is clicked counter goes to one and so on. So far it only goes up to the number one.
我的js代码是:
var $ = function (id) { return document.getElementById(id); };
var counter;
function start(){
var button = document.getElementById("button");
window.addEventListener("click", count, false);
};
function count(){
counter = document.getElementById("counter");
counter = counter+1;
document.getElementById("count").innerHTML = counter;
};
window.addEventListener("load", start, false);
我的html代码是:
<html>
<head>
<title>12.5 valenti</title>
<meta charset = "uft-8">
<script type="text/javascript" src="12.5.js"></script>
</head>
<body>
<div>
<p><input type = "button" id="button" value = "button"></p>
<p> count: <span id = "count">0</span></p>
</div>
</body>
</html>
推荐答案
您的页面上没有ID #counter
,并且您需要获取 textContent
#count 中的>,然后将其转换为整数以向其中添加数字.
You don't have an ID #counter
on the page, and you need to get the textContent
of #count
and convert it to an integer to add a number to it.
此行
counter = document.getElementById("counter");
应该是
counter = parseInt(document.getElementById("count").textContent);
var $ = function(id) {
return document.getElementById(id);
};
var counter;
function start() {
var button = document.getElementById("button");
window.addEventListener("click", count, false);
};
function count() {
counter = parseInt(document.getElementById("count").textContent);
counter = counter + 1;
document.getElementById("count").innerHTML = counter;
};
window.addEventListener("load", start, false);
<p><input type="button" id="button" value="button"></p>
<p> count: <span id="count">0</span></p>
这篇关于计算按下按钮的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文