问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/16885880/jquery-how-to-know-when-a-table-row-loses-focus