繁体   English   中英

单击按钮即可添加值

[英]Add a value upon button click

我正在尝试制作一个在单击时会添加值的按钮。 我有这段代码,怎么了?

    <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);       
});

考虑以下代码:您只需要在单击按钮后更新文本,就无需创建间隔来查看更改

 var doughnut = 0; var showText = function() { document.getElementById("doughnuts").innerHTML = "You have " + doughnut++ + " doughnuts!"; } $('button').click(function(){ showText() }); setInterval(function(){ showText(); }, 1000); showText(); 
 <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> 

  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(); 
 <div id="doughnuts"></div> <button id="btn">Click Me</button> 

关闭,但在这里:(不需要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/

更改为

$('#doughnuts').html("You have " + (doughnut+1) + " doughnuts!");
  doughnut++;

单击按钮内部将为您完成工作。

演示: https : //jsfiddle.net/ymvcauyj/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM