如何在第5个零后增加1?

时间:2017-02-20 05:19:24

标签: jquery html

我试图在第5个零点后增加1但是当我点击向上按钮时它只显示1而不是000001.

<div class="input-group spinner">
    <input type="text" class="form-control" value="000001">
    <div class="input-group-btn-vertical">
       <button class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
       <button class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
   </div>
</div>

的jQuery

<script>                          
(function ($) {
   $('.spinner .btn:first-of-type').on('click', function() {
      $('.spinner input').val( parseInt($('.spinner input').val(), 10) + 1);
   });
   $('.spinner .btn:last-of-type').on('click', function() {
      $('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
   });
})(jQuery);
</script>           

4 个答案:

答案 0 :(得分:1)

我想你应该试试

 $('.spinner input').val( "00000"+(parseInt($('.spinner input').val(), 10) + 1));

 $('.spinner input').val( "00000"+(parseInt($('.spinner input').val(), 10) - 1));

因为parseInt()只返回整数值,不包括零

答案 1 :(得分:1)

试试这个

  var noOfZer = 6; // Total length of number, for you number is 6
  var num=parseInt($('.spinner input').val(), 10) - 1;
  console.log(String('000000' + num).slice(-1 * noOfZer));

demo

答案 2 :(得分:1)

您可以查看下面的代码。实际上问题出在parseInt。如果您执行000002之类的字符串,则会得到2的结果。因此,在进行数学计算之后,我们再次需要通过按照长度预先设置零来制定所需的字符串:

&#13;
&#13;
(function($) {
  $('.spinner .btn:first-of-type').on('click', function() {
    $('.spinner input').val(prependZero(parseInt($('.spinner input').val(), 10) + 1, 6));
  });
  $('.spinner .btn:last-of-type').on('click', function() {
    $('.spinner input').val(prependZero(parseInt($('.spinner input').val(), 10) - 1, 6));
  });

  function prependZero(num, size) {
    if (num <= 0)
      num = 0;
    var s = num + "";
    while (s.length < size) s = "0" + s;
    return s;
  }

})(jQuery);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="input-group spinner">
  <input type="text" class="form-control" value="000001">
  <div class="input-group-btn-vertical">
    <button class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
    <button class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
  </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用String.slice方法,如下所示:

这里n是数字

var output = [], n, padded;
for (n=0; n<=9999; n++) {
    padded = ('0000'+n).slice(-4); // Prefix three zeros, and get the last 4 chars
    output.push(padded);
}
console.log(output); // ["0000", "0001", ..., "9999"]

http://jsfiddle.net/qJSBg/