簡體   English   中英

模糊觸發變更事件

[英]Blur to trigger Change event

我有以下代碼:

$('.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的功能,只要change功能發生?

看看這個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;
            }
        }
    })();

});

您能否將代碼移動到如下所示的函數中:

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”標記。 例如:

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;
});

從注釋中,我在一個函數中進行了全部操作,手動檢查了值:

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM