如果输入已达到 7 位数字,则停止该功能

if input has reached 7 digits, stop the function

所以基本上我有一个按钮 .button,每次按下它都会在我的输入 #number 中添加一个数字。 现在,当我的输入 #number 中已经有 7 位数字时,我希望函数喜欢 'stop working'.

这是我的代码(工作正常):

  function nrtwo(hello){
            var das = $(hello).html();
            var tempNum = $("#number").val();
            $("#number").val(tempNum + '' + das);
            tempNum = null;
        };

        $(".button").click(function(){
            nrtwo(this);
        });

我在想这样的事情?

if ($("#number").attr('maxlength') == '7') {
                return false;
            }

感谢您的帮助。

一种方法是使用.length 属性。 请试试这个:

if ($("#number").val().length == '7') {
     return false;
}

$('#add').click(function() {
  if ($("input").val().length != '7') {
     $('input').val(parseInt($('input').val())+1);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="999998"/>
<button type="button" id="add">Add</button>

您需要在点击事件本身中处理这种情况。请看下面的例子:

$(".button").click(function(){
  if ($("#number").val().length <= 7) {
    nrtwo(this);
  }
});

只有当输入的长度小于或等于 7 时,才会调用 nrtwo 方法。

试试这个 .length 它是一个 Number 和非盲 click 事件,当你达到 7 位数时:

工作jsFiddle

$(".button").click(function(){

 if ($("#number").val().length == 7) {
     $(this).unbind('click');
     return false;
 }else{
     nrtwo(this);
 }

});

如果您只处理数字,您也可以在添加之前检查数值。

$('#add').click(function() {
  var value = parseInt($('#output').val());
  if(value <= 999999) {
    $('#output').val(value + 1);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<input type="text" id="output" value="999995" />

$('#number').keypress(function(event){
        var n = $(this).val();
        if(n.length == 7){
            event.preventDefault(); //stop character from entering input
        }
       if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
           event.preventDefault(); //stop character from entering input
       }

   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="number"/>