变量不会保存在相同的函数jquery中

时间:2016-10-18 11:41:21

标签: jquery

我试图对动态创建的输入求和,但是当我删除一些输入只是为了从var中减去它的值时,当我警告变量当前它的NaN



$(document).ready(function() {
  current = 0;
  var max = 3;

  $(".inputs").on('keyup', '.field', function(e) {
    if ($('.field').val()) {
      current = current + parseInt($(this).val());
      if (current < max) {
        $(".inputs").append('<div><input type="text" class="field" name="dynamic[]" value="" /></div>');
      }
      if (e.keyCode == 8) {
        current = current - parseInt($(this).val());
        console.log(current);
      }
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <form>
    <div class="inputs">
      <div>
        <input name="dynamic[]" id="field" class="field" value="" type="text">
      </div>
    </div>
    <input name="submit" class="submit" value="Submit" type="button">
  </form>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我不确定这是你想要的,但它修复了你的NaN
它确实增加了任何密钥的电流,但

$(document).ready(function() {
  current = 0;
  var max = 3;

  $(".inputs").on('keyup', '.field', function(e) {
    var val = $(this).val();
    val = isNaN(val) || val == "" ? 0 : parseInt(val, 10);
    current = current + val;
    if (current < max) {
      $(".inputs").append('<div><input type="text" class="field" name="dynamic[]" value="" /></div>');
    }
    if (e.keyCode == 8) {
      current -= val;
    }
    console.log(current);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <form>
    <div class="inputs">
      <div>
        <input name="dynamic[]" id="field" class="field" value="" type="text">
      </div>
    </div>
    <input name="mySubmit" class="submit" value="Submit" type="button">
  </form>
</div>

也许你想要这样做:

function getInt(str) {
  return isNaN(str) || $.trim(str) == "" ? 0 : parseInt(str, 10);
}
var total = 0,
  max = 3;
$(document).ready(function() {
  $(".inputs").on('keyup', '.field', function(e) {
    var val = getInt($(this).val());
    total = 0;
    $(".field").each(function() {
      total += getInt($(this).val());
      if ($(this).val() =="") $(this).remove();
    });
    console.log(total);
    if (total > 0 && total < max) {
      $(".inputs").append('<div><input type="text" class="field" name="dynamic[]" value="" /></div>');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <form>
    <div class="inputs">
      <div>
        <input name="dynamic[]" id="field" class="field" value="" type="text">
      </div>
    </div>
    <input name="mySubmit" class="submit" value="Submit" type="button">
  </form>
</div>

答案 1 :(得分:0)

您需要检查以确保parseInt不会失败:

// check for native isNaN:
if (!Number.isNaN) {
  Number.isNaN = function(n) {
    return n !== n;
  };
}

var num = parseInt($(this).val(), 10); // always provide radix to parseInt

if (!Number.isNaN(num)) {
  current += num;
}

另一种(尽管不够)帮助验证输入的方法是将输入类型从文本更改为数字。