我正在尝试制作一个可以在点击时添加值的按钮。 我有这个代码,出了什么问题?
<div id="doughnuts">
</div>
<div id="button">
<button>CLICK to +1</button>
</div>
var doughnut = 0;
window.setInterval(
function () {
doughnut = doughnut + 1;
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
$('button').click(function(){
doughnut = Number(doughnut) + Number(1);
});
答案 0 :(得分:0)
考虑以下代码:您只需在单击按钮后更新文本,无需创建间隔以查看更改
var doughnut = 0;
var showText = function() {
document.getElementById("doughnuts").innerHTML = "You have " + doughnut++ + " doughnuts!";
}
$('button').click(function(){
showText()
});
setInterval(function(){
showText();
}, 1000);
showText();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="doughnuts">
</div>
<div id="button">
<button>CLICK to +1</button>
</div>
&#13;
答案 1 :(得分:0)
var doughnut = 0;
// Define a function,
// which you can reuse for the task (inc & set in the DOM)
var incrementAndSet = function () {
doughnut = doughnut + 1;
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}
// Reuse the function where you want.
// increment and set each second
window.setInterval(incrementAndSet, 1000);
// increment and set on click
document.getElementById('btn').onclick = incrementAndSet;
// initialize
incrementAndSet();
&#13;
<div id="doughnuts"></div>
<button id="btn">Click Me</button>
&#13;
答案 2 :(得分:0)
关闭但是在这里:(不需要Number
var doughnut = 0;
window.setInterval(
function() {
doughnut = doughnut + 1;
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
$('button').click(function() {
doughnut = doughnut+1;
});
这是一个小提示,表明它的工作:https://jsfiddle.net/MarkSchultheiss/9wdbbu6s/
答案 3 :(得分:0)
将行更改为
$('#doughnuts').html("You have " + (doughnut+1) + " doughnuts!");
doughnut++;
单击按钮内的将为您完成工作。