我有一个输入类型编号
<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 var..所以有关于如何做到这一点的线索吗?非常感谢!
最佳答案
您可以利用每个 HTMLInputElement 必须存储先前值的某些属性,例如 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" />
关于javascript - jQuery 检查输入值是否随变化而增加/减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31598591/