计算按下按钮的次数

时间:2017-02-27 02:42:50

标签: javascript html

我必须制作一个按钮,每次点击它都会向计数器添加一个按钮。 SO计数器看起来像这样。计数器:0然后一旦点击按钮,计数器转到一个,依此类推。到目前为止,它只能达到第一。

我的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>

3 个答案:

答案 0 :(得分:2)

页面上没有ID #counter,您需要获取textContent #count并将其转换为整数才能为其添加数字。< / p>

这一行

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>

答案 1 :(得分:0)

干得好......

    var clicks = 0;
    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    <button type="button" onClick="onClick()">Click me</button>
    <p>Clicks: <a id="clicks">0</a></p>

答案 2 :(得分:0)

尝试以下方法:

&#13;
&#13;
var my_button = document.getElementById('myButton');
myButton.addEventListener('click', function(){
	++document.getElementById('counter').innerHTML;
});
&#13;
<input type="button" id="myButton" value="Click"/>
Counter: <label id="counter"></label>
&#13;
&#13;
&#13;