< input>上的jQuery Change事件元素 - 任何保留先前价值的方式? [英] jQuery Change event on an <input> element - any way to retain previous value?
问题描述
我今天早上一直在搜索,我没有找到任何简单的解决方案...基本上,我想捕获一个输入元素的变化,但也知道以前的值。
I've been searching around this morning and I'm not finding any simple solutions... basically, I want to capture a change in an input element, but also know the previous value.
这是一个更改事件和一个简单形式的输入元素。显然,我可以用$(elem).val()获取新的值,但是我有一个偷偷摸摸的方法来获取以前的值?我没有看到jQuery API中的任何东西来做到这一点,但是也许有人已经这样做了,并且有一些提示?
Here's a change event and an input element in its simplest form. Clearly, I can get the new value with $(elem).val(), but is there a sneaky method I'm missing for getting the previous value? I don't see anything in the jQuery API to do this, but maybe someone's already done this and has some tips?
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
//var oldvalue = ???
var newvalue = $(this).val();
});
});
</script>
<input id="myInputElement" type="text">
我不反对编写自己的解决方案,我只是想确保我没有重新创建这里的轮子。
I'm not against writing my own solution, I just want to make sure I'm not recreating the wheel here.
推荐答案
更好的方法是使用.data存储旧值。这将备份创建一个全局变量,您应该远离并保留元素中封装的信息。关于为什么Global Vars是坏的一个真实世界的例子被记录在案这里
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here
例如
<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">
这篇关于< input>上的jQuery Change事件元素 - 任何保留先前价值的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!