I've noticed a rather odd behavior when running a unit test which passed on PhantomJS but occasionally failed in Chrome, Firefox and IE. In a nutshell:
element.focus()
, yet the listener was not run. element.focus()
for a second time actually ran the listener. Unfortunately I couldn't reproduce this issue in a fiddle, but it can be done, for instance, in jQuery's website. I do the following steps on Chrome:
$("input[name=s]").on("focus", () => console.log("a"));
. $("input[name=s]").focus();
. No output is generated. $("input[name=s]").focus();
. Now "a" is printed to the console for the first time! What is causing this issue and how could I work around it?
Had a quick delve around the jquery source code, and it seems that focus actually uses focusin, and the code is trying to map to focusin. so if you try this:
$("input[name=s]").on("focusin", () => console.log("a"));
$("input[name=s]").focusin();
it will work. There is a difference between focus and focusin around bubbling:
http://api.jquery.com/focusin/
The focusin event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the focus event in that it supports detecting the focus event on parent elements (in other words, it supports event bubbling).
It seems like the behaviour is a hard to replicate bug, that must be caused by other bit of code somewhere (maybe a lib). Although the code above should help work around it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.