jQuery检查输入值是否随变化而增加/减少

jQuery check if input value increases/decreases on change

本文关键字:增加 减少 变化 检查 输入 是否 jQuery      更新时间:2023-09-26

我有一个输入类型number

<input type="number" value="5" id="nmovimentos"/>

当值增加或减少时,我想做一个特定的动作(警报为一个简单的例子)。

我有以下jQuery代码:
$(document).ready(function(){
    var oldValue = $("#nmovimentos").val();
  $("#nmovimentos").change(function(){
    var newValue = $(this).val();
    if (newValue > oldValue)
        alert("increase!");
     else
         alert("decrease!");
  });
});

但是它不能工作,因为它不能检测oldValue变量。有什么线索吗?非常感谢!

Jsfiddle

你可以利用一些属性每个htmlputelement必须存储以前的值,例如defaultValue。在本例中,您节省了几行代码,并使代码更简洁:

$("#nmovimentos").change(function () {
    var direction = this.defaultValue < this.value
    this.defaultValue = this.value;
    if (direction) alert("increase!");
    else alert("decrease!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="5" id="nmovimentos" />

更新处理程序中的oldValue

$(document).ready(function() {
 var oldValue = $("#nmovimentos").val();
  $("#nmovimentos").change(function() {
    var newValue = $(this).val();
    if (newValue > oldValue)
      console.log("increase!");
    else
      console.log("decrease!");
    oldValue = newValue;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="number" value="5" id="nmovimentos" />

,使用data-*属性来跟踪

$(document).ready(function() {
  $("#nmovimentos").attr('data-prev-val', $("#nmovimentos").val());
  $("#nmovimentos").change(function() {
    var newValue = $(this).val();
    if (newValue > $(this).attr('data-prev-val'))
      console.log("increase!");
    else
      console.log("decrease!");
    $("#nmovimentos").attr('data-prev-val', newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="number" value="5" id="nmovimentos" />

您必须首先将旧值保存在某个地方。jQuery.data()是很方便的。

$(document).ready(function(){
  var nmovimentos = $("#nmovimentos");
  var oldValue = nmovimentos.val();
  nmovimentos.data("oldValue", oldValue);
  
  $("#nmovimentos").change(function(){
    var oldValue = $(this).data("oldValue");
    var newValue = $(this).val();
    if (newValue > oldValue)
        alert("increase!");
     else
         alert("decrease!");
    $(this).data("oldValue", newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" value="5" id="nmovimentos"/>