3

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

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

4

4 回答 4

10

不是直接的,但您可以将值存储在focusevent..

就像是

$('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
        }
    });

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

$('input')
   .on('change', function(){/*your change code*/})
   .on('blur', function(){/*your blur code*/});
于 2013-05-23T09:33:18.197 回答
3

每次字段失去焦点且内容发生变化时触发事件变化。我认为你需要的是使用change()而不是blur(). 看看这个jsfiddle

$('#in').change(function(){
    alert('change!');
});

如果您需要在输入失去焦点和值更改时执行相同的代码,您可以将这两个事件结合起来

$('in').on('change blur', function(){
   //code
});
于 2013-05-23T09:32:49.057 回答
0

您可以使用闭包来存储先前的值并稍后进行比较

var createOnBlurFunc = function(){
    var prevVal = '';
    return function(e){
        if(prevVal === $(this).val()){
           //same value
        } else {
           prevVal = $(this).val();
           // do something
        }
     }
};
$('input').blur(createOnBlurFunc());
于 2013-05-23T09:39:14.423 回答
0

我认为这是一种更通用的方式,对于那些动态创建的方式:

var $bodyEl = $('body'), inputOldValue;

$bodyEl.on('focus', 'input, textarea, select', function () {
    inputOldValue = $(this).val();
});
$bodyEl.on('blur', 'input, textarea, select', function () {
    if (inputOldValue != $(this).val()) {
        $(this).trigger('changeBlur');
    }
});

input, textarea, select:input作为选择器更快。

于 2016-01-21T12:52:15.893 回答