簡體   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