Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

javascript - Focus and blur jQuery events not bubbling

With the following html structure:

<div>
<form><span><input></span></form>
</div>
<p>

and the following jquery code:

$('form').on("focus", function(event) {
    $("p").append("focus no delegation<br>");
})

Why doesn't the focus event ever reach my event handler? Binding the event with a selector parameter works fine:

$('form').on("focus", "input", function(event) {
    $("p").append("focus delegation<br>");
})

Event the next snippet works so the focus event does in fact bubble...

$('form').on("focus", "span", function(event) {
    $("p").append("focus delegation<br>");
})

Both forms work with click and change events:

$('form').on("click", function(event) {
    $("p").append("click no delegation<br>");
})
$('form').on("click", "input", function(event) {
    $("p").append("click delegation<br>");
})

The only note I found about the focus event's bubbling is relative to older jQuery versions which I don't use. See it in action here

edit 1

Well this is confusing... According to jQuery's focus doc:

The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods, .live() and .delegate().

And according to jQuery's focusin doc:

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).

Is it too late for me or does one contradict the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Ohgodwhy pointed out, using focusin instead of focus does work.

However, I can't understand how the following code can work if the "focus" event does not bubble:

$('form').on("focus", "span", function(event) {
    $("p").append("focus delegation<br>");
})

If a span child of the form receives the "focus" event, it means that the event bubbled from the input to the span. Even this works!

$('div').on("focus", "form", function(event) {
    $("p").append("focus delegation<br>");
})

So... using "focusin" does fix the problem, but I'm not fully satisfied by this workaround. If anybody has a better answer, I'll happily accept it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...