简体   繁体   English

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

[英]Focus event doesn't fire on input fields (no jQuery)

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...对此的任何帮助将是超级...

Turns out you need to set the 'useCapture' option to true.原来您需要将 'useCapture' 选项设置为 true。 If you want to know more about 'useCapture' option, this StackOverflow question does a better job than MDN.如果您想了解更多关于“useCapture”选项的信息, 这个 StackOverflow 问题比 MDN 做得更好。

Just means I had to change from this:只是意味着我必须改变这一点:

addEventListener('focus', handleFocus, false);

...to this: ...到这个:

addEventListener('focus', handleFocus, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM