<input> 上的 jQuery Change 事件元素 - 有什么办法可以保留以前的价值? [英] jQuery Change event on an &lt;input&gt; element - any way to retain previous value?

查看:28
本文介绍了<input> 上的 jQuery Change 事件元素 - 有什么办法可以保留以前的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早上我一直在四处搜索,但没有找到任何简单的解决方案……基本上,我想捕获输入元素中的更改,但也想知道以前的值.

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 存储旧值.这避免了创建全局变量,您应该远离它并将信息封装在元素中.记录了一个关于全局变量为什么不好的真实示例 这里

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆