每次在jQuery中单击按钮时,如何使输入添加值?

时间:2018-09-23 19:32:38

标签: javascript jquery html5

我有要单击的按钮,当它单击时,我希望该值增加被单击的相同值; 这是我的html

          <div  id="setTimer">
                <div class="spans">
                  <span   class="timeSet" >1</span>
                  <span  class="timeSet">2</span>
                  <span  class="timeSet">3</span>
                  <span  class="timeSet">4</span>
                </div>
                <div class="spans">
                    <span  class="timeSet">5</span>
                   <span  class="timeSet">6</span>
                   <span  class="timeSet">7</span>
                   <span  class="timeSet">8</span>
                </div>
                <div class="spans">
                    <span  class="timeSet">9</span>
                    <span  class="timeSet">0</span>
                    <span  class="timeSet">+30s</span>
                </div>             
            </div>

javascript

$(document).ready(function(){
        var count = 0
        var btnCountOutput = $('#btnCountOutput');
    var txt = $(this);
    $('.timeSet').click(function(txt){
        count++;
        if(count > 3){
            console.log('that cant be done!');
            return false;
        }
        var output = txt.currentTarget.innerHTML;
        output++;
        var num = parseFloat(output);
        var inputOut = btnCountOutput.val(num);
        console.log(num);
        console.log(count);
    });
});

输出的HTML

<div class="timeCount">
    <input type="text" placeholder="Buttonclick Counter" class="col" 
     id="btnCountOutput">

CSS(如果需要)

#setTimer .spans{
margin-bottom: 10px;
  }
 #setTimer span{
   width: 15px;
   height: 10px;
   border-radius:50%;
   background: white;
   text-align: center;
   padding: 4px;
   cursor: pointer;
}

好吧,就像我可以编写的 Java脚本一样;

  btnCountOutput.value += num;

每次单击按钮时,只需在输出上添加所有被单击的值

1 个答案:

答案 0 :(得分:1)

您需要获取文本框的值,然后将其添加到传递的数字中。添加完成后,您可以再次设置文本框的值。我添加了一个名为currentCount的变量作为示例:

https://jsfiddle.net/mswilson4040/487eaopt/

$(document).ready(function() {
  var count = 0
  var btnCountOutput = $('#btnCountOutput');
  var txt = $(this);
  $('.timeSet').click(function(txt) {
    count++;
    if (count > 3) {
      console.log('that cant be done!');
      return false;
    }
    var output = txt.currentTarget.innerHTML;
    output++;
    var num = parseFloat(output);
    var currentCount = btnCountOutput.val(); // Grab the current value
    var inputOut = btnCountOutput.val(+num + +currentCount); // Add the two values together and set the text box (make sure to convert string to number)
    console.log(num);
    console.log(count);
  });
});

您也不需要parseFloat函数。您确实需要一些函数来确保将字符串转换为数字,但是您需要NumberparseInt+。除非您要使用十进制值,否则不需要parseFloat