ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 聚焦和模糊jQuery事件而不是冒泡

2019-09-29 03:37:13  阅读:117  来源: 互联网

标签:javascript jquery event-handling


使用以下html结构:

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

和以下jquery代码:

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

为什么焦点事件没有到达我的事件处理程序?使用选择器参数绑定事件可以正常工作:

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

活动下一个片段的作用,所以焦点事件实际上泡沫……

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

两种形式都适用于点击和更改事件:

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

我发现关于焦点事件冒泡的唯一注意事项是相对于我不使用的旧jQuery版本.在行动here中看到它

编辑1

这很令人困惑……根据jQuery的焦点文档:

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

根据jQuery的焦点文档:

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

对我来说为时已晚还是与另一方相矛盾?

解决方法:

是的,似乎jQuery文档具有误导性.我认为关于焦点的文档忽略了提到这是针对不涉及用户输入的元素(@Ohgodwhy在你的问题的评论中将它们列在上面).

我想这与浏览器需要将光标捕获到具有焦点的输入元素有关,因此它可以接受来自键盘的输入.换句话说,如果jQuery允许它冒泡,那么你永远不会有机会输入输入字段.

无论哪种方式,你永远不会得到一个表单来接受焦点事件,除非你首先在它上面添加一个tabindex:http://jsfiddle.net/qxLqP/但是如果基于输入的字段首先获得焦点,它将永远不会冒泡.默认情况下,表单元素没有tabindex,并且您无法将焦点设置为没有tabindex的内容.

我只是接受@ Ohgodwhy使用focusin的解决方案,然后让jQuery团队了解他们令人困惑的文档.

标签:javascript,jquery,event-handling
来源: https://codeday.me/bug/20190929/1830370.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有