焦点事件不会在输入字段上触发(没有jQuery)

时间:2022-11-13 19:59:39

For some reason the following code only fires when the window gets focus, but not when input fields get focus, or any other element (regardless of whether they have a tabindex or not).

由于某种原因,以下代码仅在窗口获得焦点时触发,而不是在输入字段获得焦点时触发,或者在任何其他元素(无论它们是否具有tabindex)时触发。

I don't want to use someElement.addEventListener method, because the element isn't attached to the view at the time the event listener is added.

我不想使用someElement.addEventListener方法,因为在添加事件侦听器时元素未附加到视图。

var handleFocus = function(event) {
   var el = event.target;
   console.log(el);
}

addEventListener('focus', handleFocus, false);

I basically need to listen for when any input fields are focused on. My reason for wanting to apply it to the parent window, is that the form fields are added and removed from the view at different times (Aurelia).

我基本上需要监听何时关注任何输入字段。我想将它应用于父窗口的原因是表单字段在不同时间(Aurelia)添加和删除。

When the event fires, I want to be able to read properties of the target, to see what actions I need to take.

当事件触发时,我希望能够读取目标的属性,以查看我需要采取的操作。

Any help on this would be super...

任何有关这方面的帮助都会超级......

1 个解决方案

#1


2  

Turns out you need to set the 'useCapture' option to true. If you want to know more about 'useCapture' option, this * question does a better job than MDN.

事实证明,您需要将'useCapture'选项设置为true。如果您想了解有关'useCapture'选项的更多信息,那么这个*问题比MDN做得更好。

Just means I had to change from this:

只是意味着我必须改变这一点:

addEventListener('focus', handleFocus, false);

...to this:

addEventListener('focus', handleFocus, true);

#1


2  

Turns out you need to set the 'useCapture' option to true. If you want to know more about 'useCapture' option, this * question does a better job than MDN.

事实证明,您需要将'useCapture'选项设置为true。如果您想了解有关'useCapture'选项的更多信息,那么这个*问题比MDN做得更好。

Just means I had to change from this:

只是意味着我必须改变这一点:

addEventListener('focus', handleFocus, false);

...to this:

addEventListener('focus', handleFocus, true);