jQuery: How to know when a table row loses focus?

会有一股神秘感。 提交于 2020-01-14 10:27:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!