[英]How to prevent BLUR event from firing multiple times?
I have certain text input fields where if users change a value and then blur away from that text field, the js will fire and ajax request to update that value in the db. 我有某些文本输入字段,如果用户更改了一个值然后模糊了该文本字段,则js将触发并用ajax请求更新数据库中的该值。 The problem is that I wrote a test to get such an event to fire and I notice that the inner 'blur' event usually fires between two and five times after I tab out of the input field: 问题是我编写了一个测试来触发此类事件,并且我注意到,在我跳出输入字段后,内部“模糊”事件通常会触发2至5次:
$('input[type=text]').on('input propertychange paste', function() {
$(this).on('blur', function () {
console.log('blur');
});
});
Even if I turn off the blur event handler right after catching it, it still fires two or three times. 即使我在捕捉到模糊事件处理程序后立即将其关闭,它仍然会触发两次或三次。 How do I get this to happen only once? 我如何使这种情况只发生一次?
Just keep track of a hasFired
boolean: 只需跟踪hasFired
布尔值即可:
var hasFired = false;
$('input[type=text]').on('input propertychange paste', function() {
$(this).on('blur', function () {
if(!hasFired){
hasFired = true;
console.log('blur');
}
});
});
Actually, the real problem here is that you're binding the blur
event multiple times. 实际上,这里的真正问题是您多次绑定了blur
事件。 You can use a boolean like above to prevent that: 您可以使用上面的布尔值来防止这种情况:
var isBound = false;
$('input[type=text]').on('input propertychange paste', function() {
if(!isBound){
isBound = true;
$(this).on('blur', function () {
console.log('blur');
});
}
});
Another solution would be is to create a class for those elements that already bound by that event. 另一个解决方案是为该事件已绑定的那些元素创建一个类。
$('input[type=text]').on('input propertychange paste', function() {
if(!$(this).hasClass("bound")) {
$(this).on('blur', function () {
$(this).addClass("bound");
console.log('blur');
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.