Jquery:作用于形式的 .blur(),而不是元素

Jquery: function on .blur() of form, not elements

我在社区中搜索了一下,看到有很多关于如何为表单元素制作 on(blur(function)) 或 on(focusout(function)) 的指导,但我没有看到当表单本身失去焦点时,模糊元素就会出现。我想要那种依赖于在提交之前更新两个字段的行为,但是如果我在一个字段上有效 onblur() 它会给出一个错误的错误,因为用户没有机会更新另一个字段。

这里是我的基本概念的代码:

$(document).ready(function(){
    $("form").blur(function(){
        alert("This form has lost its focus.");
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

<form>
Enter your name: <input type="text">
Enter your age: <input type="text">
</form>
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>

</body>
</html>

如果我让 .ready 语句专注于 "input",而不是 it works fine,但是当我希望文档监控整个表单时完全没有响应。有任何想法吗?谢谢!

您要查找的活动不是 blur,而是 focusout。如果我们将 focusout 事件绑定到表单本身,则只要焦点丢失在表单内的任何元素上,就会调用处理程序。

另请注意,我添加到各种元素的 tabindex 属性与这段代码的工作无关。添加它们是因为对您的 post 声称表单无法聚焦的错误评论。

从这里开始tabindex

The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key, hence the name). It accepts an integer as a value, with different results depending on the integer's value:

  • A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. Mostly useful to create accessible widgets with JavaScript.

如您所见,任何元素都可以获得焦点。只是只有某些元素 默认获得焦点(锚点、输入、按钮等),而无需为它们设置 tabindex。在下面的示例中,如果您单击“输入您的姓名”文本,您将看到表单本身获得焦点。然后您可以跳转到输入,然后是 div,最后是跨度。依次获得焦点

$('#theForm').on('focusout', function(e) {
  // do what you want/need to do here
  console.log('Form has lost focus');
});
#theDiv {
  height: 50px;
  width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="theForm" tabindex="1">
Enter your name: <input type="text" tabindex="2">
Enter your age: <input type="text" tabindex="3">
</form>
<div id="theDiv" tabindex="4"></div>
<span tabindex="5">Some Text</span>
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>