我今天早上一直在寻找,但我没有找到任何简单的解决方案...基本上,我希望捕获输入元素中的更改,但也要知道以前的值。
下面是一个最简单形式的change事件和一个input元素。显然,我可以使用$(elem).val()来获得新值,但是有没有一种偷偷摸摸的方法来获得以前的值呢?我在jQuery应用程序接口中看不到任何可以做到这一点的东西,但也许有人已经做到了这一点,并且有一些技巧?
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
//var oldvalue = ???
var newvalue = $(this).val();
});
});
</script>
<input id="myInputElement" type="text">
我不反对写我自己的解决方案,我只是想确保我不是在这里重新创建轮子。
发布于 2009-07-21 13:38:20
一种更好的方法是使用.data存储旧值。这就省去了创建全局var的麻烦,您应该避免创建全局var,并将信息封装在元素中。关于全局变量为什么不好的一个真实例子是有文档记录的here
e.g
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
发布于 2011-07-14 19:46:13
这可能会起到作用:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("old", $(this).data("new") || "");
$(this).data("new", $(this).val());
console.log($(this).data("old"));
console.log($(this).data("new"));
});
});
发布于 2014-04-18 18:19:16
$('#element').on('change', function() {
$(this).val($(this).prop("defaultValue"));
});
https://stackoverflow.com/questions/1159046
复制相似问题