找出模糊的值与“焦点”的值相比是否不同.(JavaScript + jQuery)

Find out if the value on blur is different as compared with "the focus one" (JavaScript + jQuery)

本文关键字:JavaScript 是否 jQuery 模糊 焦点      更新时间:2023-09-26

我试图找出如果用户改变文本字段或选择选项,如果是这样,然后做一些东西。我也在用jQuery

$('.c').on('focus',function(){
    var origval=this.value;
    $(this).on('blur',function(){
        var newval=this.value;
        if(origval==newval){
            alert('not changed');
        }
        else{
            alert('changed');
        }
    });
});

但这不是正确的解决方案,我做错了什么。有时它会提醒"改变了",尽管它不应该这样做。谁能告诉我故障在哪里?谢谢你。

http://jsfiddle.net/QGag2/1/

blur事件被订阅了多次,因为这发生在每个焦点上。

在订阅之前取消订阅blur事件(off方法),或者在blur发生后取消订阅事件。

$(this).off('blur').on('blur',function(){

您不必嵌套事件处理程序。它们可以像下面这样独立,当一个(focus)出现时,值被保存,当另一个(blue)出现时,比较完成。

$(function() {
    var formElement = $( '.c' );
    formElement.on( 'focus', function() {
        $( this ).data( 'focus', this.value );
    });
    formElement.on( 'blur', function() {
        $( this ).data( 'blur', this.value );
        if( $( this ).data( 'focus' ) === $( this ).data( 'blur' ) ) {
            alert( this.nodeName +' not changed' );
        } else {
            alert( this.nodeName +' changed' );
        }
    });
});

JS FIDDLE DEMO