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.

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.

推荐答案

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">

Jquery相关问答推荐

提交表单时运行自定义验证脚本

JQuery AJAX数据表保留前导零

jQuery在页面加载 timeshift 动到锚点位置

当输入值以编程方式更改时触发更改事件?

AngularJS 中的 ScrollTo 函数

如何滚动到AngularJS中的页面顶部?

如何制作 AngularJS 指令来停止传播?

jQuery从下拉列表中删除一个选项,给定选项的文本/值

jQuery JSON到字符串?

Onchange 通过 Select 打开 URL - jQuery

iframe 仅显示页面的特定部分

验证外部脚本是否已加载

jQuery闪烁突出显示对div的影响?

更改占位符文本

jQuery 日期 Select 器 - 禁用过go 的日期

javascript jquery单选按钮单击

上传文件前验证文件扩展名

将多个参数传递给 jQuery ajax 调用

如何禁用由子元素触发的 mouseout 事件?

'touchstart' 事件是否有与点击事件相同的 e.PageX 位置?