JQuery:如何在此示例中将文本框中的值停止为负数?

时间:2015-03-03 20:15:26

标签: javascript jquery html

我是Javascript的新手,我已经掌握了一些基础知识,但是我想弄清楚如何在这个具体示例中停止文本值减少到0:http://codepen.io/anon/pen/ZYjeJb 我是否必须以某种方式更改条件语句?

    <div id="text">Number of items:<span id="number">9</span><div>

        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>
        <button onclick="javascript:add(-1)">remove only 1</button>




        var currentValue = 9;
            var add = function(valueToAdd){
            currentValue += valueToAdd;
            document.getElementById('number').innerHTML = currentValue;
            if (this.currentValue == 0) {
            alert("YOU ARE AT 0 ");
        }
        if (!isNaN(currentValue) && currentValue > 0) {
            // Decrement one
            currentValue - 1;
        } else {
            return false;
        }
    };

3 个答案:

答案 0 :(得分:0)

实际更改您的值的行是这一行

currentValue += valueToAdd; 

因此,如果在更改之前检查将要插入currentValue的值,则可以停止执行函数并阻止其更新:

function(valueToAdd){
      var temp = currentValue + valueToAdd; // calculating the next value
      if (temp < 0) 
        return; // if its a negative value, exit from the function without updating currentValue
      currentValue = temp;
      // other code
}

检查this codepen

答案 1 :(得分:0)

在检查之前不要递减currentvalue

    var add = function(valueToAdd){
    if (this.currentValue == 0) {
    alert("YOU ARE AT 0 ")}
    else{
      currentValue += valueToAdd;
     document.getElementById('number').innerHTML = currentValue;}

}

答案 2 :(得分:0)

在设置'valueToAdd'

之前,您需要检查当前值为零
var currentValue = 9;
        var add = function(valueToAdd){
          if (this.currentValue == 0) {
                alert("YOU ARE AT 0 ");
                    return
            }
            currentValue += valueToAdd;
            document.getElementById('number').innerHTML = currentValue;

            if (!isNaN(currentValue) && currentValue > 0) {
                // Decrement one
                currentValue - 1;
            } else {
                return false;
            }
        };