jQuery:如何知道表格行何时失去焦点? [英] jQuery: How to know when a table row loses focus?
问题描述
在一个表格行(< tr>
)中有几个输入元素。
在失去焦点时执行一些JavaScript代码(但不是当用户只是在同一个tr中切换到不同的输入元素时)。
我使用jQuery。 >
如何做到跨浏览器?
寻找这种方法(演示,在Chr / Ff / IE10中检查):
var delayedFn,blurredFrom;
$('tr')。on('blur','input',function(event){
blurredFrom = event.delegateTarget;
delayedFn = setTimeout(function(){
console.log('Blurred');
},0);
});
$('tr')。on('focus','input',function(event){
if(blurredFrom === event.delegateTarget){
clearTimeout(delayedFn);
}
});
正如您所看到的,我们延迟了对真正的模糊处理程序(这是 console.log
在这个例子中)和 setTimeout
- 清除这个超时,如果我们看到焦点停留在同一行。
我在这里使用委托,所以我不需要每次调用最接近(tr)
。但是这里有另一个副作用,因为处理程序会正确处理添加到表中的输入。
In a table row (<tr>
) there are several input elements.
I need to execute some JavaScript code when the tr loses focus (but not when the user just switches to a different input element in the same tr).
I use jQuery.
How to do it cross-browser?
I suppose you're looking for this approach (demo, checked in Chr/Ff/IE10):
var delayedFn, blurredFrom;
$('tr').on('blur', 'input', function(event) {
blurredFrom = event.delegateTarget;
delayedFn = setTimeout(function() {
console.log('Blurred');
}, 0);
});
$('tr').on('focus', 'input', function(event) {
if (blurredFrom === event.delegateTarget) {
clearTimeout(delayedFn);
}
});
As you see we delay the call to our "true blur handler" (which is the function with console.log
in this example) with setTimeout
- and clear this timeout if we see the focus stayed in the same row.
I use delegation here so I won't need to call closest(tr)
each time. But it has another side-effect here, as the handler will deal correctly with the inputs added to the table dynamically.
这篇关于jQuery:如何知道表格行何时失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!