Javascript 模糊触发更改事件
我有以下代码:Javascript 模糊触发更改事件,javascript,jquery,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. }); 我如何确保模糊功能在更改
$('.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.
});
我如何确保
模糊
功能在更改
功能之前发生,无论何时发生更改
功能?您是否可以将代码移动到这样的功能中:
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
}
});
不知道怎么做,但另一种方法是在
blur
函数中执行所有检查,因为live
不推荐使用时,该函数将100%触发。你应该在上使用,而不是什么是客观的?你能把这两个处理器组合起来吗?如果是,可以设置标志,如果代码已经运行,只需在blur事件中执行所有操作。您可以进行检查,查看您的值是否已更改,如果已更改,则可以运行之前在更改事件中的代码。
$(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;
}
}
})();
});
$('.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
}
});