$("#myTextBox").on("change paste keyup", function() {
alert($(this).val());
});
如何比较用户插入的新值和已存在于输入框中的当前值?
$("#myTextBox").on("change paste keyup", function() {
alert($(this).val());
});
如何比较用户插入的新值和已存在于输入框中的当前值?
$("#myTextBox").on("change paste keyup", (function() {
var previousValue = $("#myTextBox").val();
return function() {
var newValue = $(this).val();
alert('Was ' + previousValue + " and now it's " + newValue);
previousValue = newValue;
};
})());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" />
previousValue
的变量,其生命周期比处理程序函数长,但只能由此处理程序函数访问。这样可以确保在代码的其他部分不会出现名称冲突。您可以在元素本身上保存先前的值,并在值更改时获取它。
$("#myTextBox").on("change paste keyup", function() {
// Get previous and current value
var prevValue = $(this).data('value'),
currValue = $(this).val();
console.log(prevValue + ' === ' + currValue);
// Update the prevValue
$(this).data('value', currValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="myTextBox" type="text" />
value
属性实际上并没有更新。因此,您可以简单地将.val()
与attr("value")
进行比较,并在更改后更新attr("value")
:
E.G:
$("#myTextBox").on("change paste keyup", function() {
alert($(this).attr("value")+" vs "+$(this).val());
$(this).attr("value",$(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" />
基本上,您可以在JavaScript中保存任何值,您可以使用3种常见的方法保存或保留先前的数据:
最好的方法是使用变量,例如:
var previousValue = $(this).val();
然后在之后访问它...
$("#myTextBox").on("change paste keyup", function () {
var preValue = $(this).val();
return function () {
var newValue = $(this).val();
consol.log('preValue: ' + preValue + 'newValue: ' + newValue);
preValue = newValue;
};
});
返回发生在之后,所以它的工作方式类似于回调函数,基本上是在之后发生的,这样你就可以保存两个变量...