2012-04-01 97 views
2

的增加/減小值我有這樣的:jQuery的 - 跨度

  <ul class="deposit" style="float:left;list-style-type:none;"> 
       <a href="javascript:void(0)" id="inc"><li class="first">+</li></a> 
       <a href="javascript:void(0)" id="dec"><li class="second">-</li></a> 
      </ul> 

<div class="left deposit_amount">$<span id="amountSpan"></span></div> 

我想做的事情,所以每當我點擊#inc的#amountSpan將由5每當點擊了#dec增加,該值將通過5 我也希望有會下降,因此該值不能低於0

目前我有這樣的:

$(function(){ 
    $("#inc").click(function(){ 
     $("#amountSpan").val(Number($("#amountSpan").val()) + 5); 
    }); 
    $("#dec").click(function(){ 
     $("#amountSpan").val(Number($("#amountSpan").val()) - 5); 
    }); 
    }); 

但是,這是行不通的。我怎樣才能獲得這個?

在此先感謝。

更新:

我嘗試設置最大數量,這一點:

$("#inc").click(function(){ 
    $("#amountSpan").text(Math.max(20, Number($("#amountSpan").text()) + 5)) 
}); 

但它只是過去20

+0

當你試圖控制*最大*值時,你必須使用'Math.min()'。我一直都在倒退。所以在你的「inc」例程中,它應該是'Math.min(20,Number ...)',以確保該值是20中的較小值以及總和。 – Pointy 2012-04-01 12:53:51

回答

4

代替.val()(這是表單輸入元素),請使用.text()。哦,當你遞增的時候,你需要確保這個值首先是一個數字。 (哦,等等,你已經是:-)

$(function(){ 
    $("#inc").click(function(){ 
     $("#amountSpan").text(Number($("#amountSpan").text()) + 5); 
    }); 
    $("#dec").click(function(){ 
     $("#amountSpan").text(Number($("#amountSpan").text()) - 5); 
    }); 
    }); 

要保持大於或等於量爲零:

$("#amountSpan").text(Math.max(0, Number($("#amountSpan").text()) - 5)) 
+0

謝謝!有效。我愚蠢。 但我該怎麼做,所以價值/文字不能低於0? (在遞減的時候) – oliverbj 2012-04-01 12:44:13

+0

剛剛添加一個測試或者使用'Math.max()'...我會更新答案 – Pointy 2012-04-01 12:44:41

+0

謝謝!雖然你提供的math.Max沒有工作。我仍然可以低於零。 – oliverbj 2012-04-01 12:46:32

0
你可以在一年按下面的例子也

日期

<script type="text/javascript"> 
    function increment1(myInput) { 

     myInput.value = Math.min(31, (+myInput.value + 1) || 0); 
    } 
    function decrement1(myInput) { 
     myInput.value = Math.max(1, (myInput.value - 1) || 0); 
    } 
    /*myInput.value = (myInput.value - 1) || 0;*/ 

</script> 

<img src="Icalorieimage/account/increase_menu.png" 
    width="25" height="20" id="target" style="float:left; cursor:pointer;" align="left" 
    onclick="increment(this.parentNode.getElementsByTagName('input')[0]);"/> 
<img src="Icalorieimage/account/decrease_menu.png" width="25" height="20" style="float:left; cursor:pointer;" 
    align="left" 
    onclick="decrement(this.parentNode.getElementsByTagName('input')[0]);"/>