2016-02-13 183 views
0

我有这个问题。我的用户可以点击一个-按钮从总数中减去1。他们不能低于0。当我点击我的按钮到0,然后点击+按钮,可以在0以上工作。但是,当我想再次点击-按钮时,它仍然被禁用。如何启用禁用按钮jquery

这里是我的代码

$('#minderApple').click(function(){ 
    $("#appletotal").val(parseInt($("#appletotal").val()) - 1); 
    if ($('#appletotal').val() < 1){ 
     $("#minderApple").prop("disabled",true); 
    }else{ 
     $("#minderApple").prop("disabled",false); 
    } 
}); 

回答

0

的问题是因为val()返回一个字符串,你比较为整数。您可以使用parseInt()将该值转换为int。另外,您可以通过直接向prop()提供布尔值来删除if语句。试试这个:

$('#minderApple').click(function() { 
    var $appleTotal = $('#appletotal'); 
    var newVal = parseInt($appleTotal.val(), 10) - 1; 
    $appleTotal.val(newVal); 
    $(this).prop("disabled", newVal < 1); 
}); 

Working example

+0

并不能解决问题 – Wesley

+0

这不是一个有用的回应。你没有得到什么行为?你会得到什么样的行为?控制台中有任何错误?如果你点击 - 按钮确定它的工作原理,看到你的HTML也会有很大帮助 –

+0

。但是当你在输入栏中输入5并点击 - 按钮时,它不再起作用 – Wesley

0
$('#minderApple').click(function(){ 
    if ((parseInt($("#appletotal").val()) - 1) < 1){ 
     $("#minderApple").attr("disabled","disabled"); 
    }else{ 
     $("#minderApple").removeAttr("disabled"); 
    } 
}); 
+0

你还在比较字符串:int:'if($('#appletotal').val()<1)' –

+0

这并不能解决它 – Wesley

0
<html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
     <style> 

      .active { 
       color:red; 
      } 
     </style> 
    <script> 

     $(document).ready(function() { 

      $('#minderApple').click(function() { 
       $("#appletotal").val(parseInt($("#appletotal").val()) - 1); 
       if ($('#appletotal').val() < 1) { 
        $("#minderApple").prop("disabled", true); 
       } else { 
        $("#minderApple").prop("disabled", false); 
       } 
      }); 


      $('#plus').click(function() { 
       $("#appletotal").val(parseInt($("#appletotal").val()) + 1); 
       if ($('#appletotal').val() >1) { 
        $("#minderApple").prop("disabled", false); 
       } else { 
        $("#minderApple").prop("disabled", false); 
       } 
      }); 

     }); 
    </script> 
    </head> 

    <body> 
     <input type="text" id="appletotal" value="5"/> 
     <input type="button" id="minderApple" value="-"/> 
     <input type="button" id="plus" value="+"/> 

    </body> 

    </html>