模糊以触发Change事件

时间:2013-12-30 19:52:15

标签: javascript jquery

我有以下代码:

$('.subtle-input').live('blur', function() {
    // this will fire all the time
});

$('.provider-rate-card input[type="text"]').live('change', function() {
    // this will fire some of the time, only when value is changed.
});

每当blur函数发生时,如何确保change函数在<{strong> {/ 1}}函数之前发生?

3 个答案:

答案 0 :(得分:1)

查看此jsfiddle

<div class="provider-rate-card">
    <input class="subtle-input" type="text" />
</div>

$(function() {


    //This closure is simply here because you will be using a global variable
    //It helps prevent pollution of the global namespace, which is a good
    //practice in Javascript.
    (function() {
        //defines the flag
        var changed = false;

        $('.subtle-input').on('blur', function() {
            blurFunction(changeFunction);
        });

        $('.provider-rate-card input[type="text"]').on('change', function() {
            //sets the flag
            changed = true;
        });

        function blurFunction(func) {
            //do something every time it blurs
            console.log('blurred'); 

            //you will provide this callback as a parameter (see above)
            return func();
        }

        function changeFunction() {
            //checks the flag
            if(changed === true) {
                //do something whenever the value changes
                console.log('changed'); 

                //reset
                changed = false;
            }
        }
    })();

});

答案 1 :(得分:0)

您可以将代码移动到如下函数中:

var doSomething = function() {
    // do something
};

$('.subtle-input').live('blur', function() {
    // this will fire all the time
    doSomething();
});

$('.provider-rate-card input[type="text"]').live('change', function() {
    // this will fire some of the time, only when value is changed.
    doSomething();
});

或者在你的情况下,这两个事件会依次触发,以至于你不希望该函数执行两次?在这种情况下,也许你想在评论中使用像'charlietfl'这样的标志。 E.g:

var doneSomething = false;

var doSomething = function() {
    // do something
    doneSomething = true;
};

$('.subtle-input').blur(function() {
    // this will fire all the time
    doSomething();
});

$('.provider-rate-card input[type="text"]').change(function() {
    // this will fire some of the time, only when value is changed.
    if (doneSomething === false) {
        doSomething();
    }
    doneSomething = false;
});

答案 2 :(得分:0)

从评论中,我在一个函数中完成了所有操作,手动检查值:

$('.subtle-input').live('blur', function() {
    var existing_value = $(this).data('existing_value');
    var new_value = $(this).val();

    if (new_value != existing_value) {
        // do the change stuff
    }

});