拦截值在.blur()事件中发生变化

dav*_*ooh 3 javascript jquery events

.blur()每次文本字段失去焦点时都使用函数来执行一些代码(当它的值没有改变时).

现在我需要添加一些必须在文本字段值更改时才能执行的逻辑.有没有办法将.change()事件与.blur()?或者,更好的是,有没有办法知道我的文本字段中的值是否仅仅使用了.blur()

Gab*_*oli 9

不是直接的,但你可以将值存储在focus事件上.

就像是

$('input')
    .on('focus',function(){
        // store the value on focus
        $(this).data('originalValue', this.value);
    })
    .on('blur',function(){
        // retrieve the original value
        var original = $(this).data('originalValue');

        // and compare to the current one
        if (original !== this.value){
            // do what you want
        }
    });
Run Code Online (Sandbox Code Playgroud)

当然,您可以为每个事件绑定不同的处理程序.

$('input')
   .on('change', function(){/*your change code*/})
   .on('blur', function(){/*your blur code*/});
Run Code Online (Sandbox Code Playgroud)