javascript jquery settimeout 和 .focus() 一起在 firefox 浏览器中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10278139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:17:45  来源:igfitidea点击:

jquery settimeout and .focus() together not working in firefox browser

javascriptjqueryerror-handlingfocussettimeout

提问by Sekhar

I have a form which when submitted(empty fields) displays spring validated errors in the front end jsp . I need to focus the display in the first error message displayed in the front end. Generated code from the form (via view source): For example 2 error message enclosed inside div element. I need to focus it on the first error message.

我有一个表单,当提交时(空字段)在前端 jsp 中显示弹簧验证错误。我需要在前端显示的第一条错误消息中集中显示。从表单生成的代码(通过查看源代码):例如 div 元素内包含的 2 条错误消息。我需要把它集中在第一条错误信息上。

      <div id="userid.errors" class="lp">User id is missing</div>
      <div id="age.errors" class="lp">age is missing</div>

I tried the below jquery code, but it works only in IE and not in firefox. In firefox , focus is not working eventhough css style handled properly.

我尝试了下面的 jquery 代码,但它仅适用于 IE 而不适用于 Firefox。在 firefox 中,即使正确处理了 css 样式,焦点也不起作用。

I am sure syntax and logic is correct - could some one help me out in fixing it for firefox browser ?

我确信语法和逻辑是正确的 - 有人可以帮我修复它的 Firefox 浏览器吗?

<script type="text/javascript" src="/scripts/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/jquery.validate.js"></script>

 <script type="text/javascript">

 $(document).ready(function() {
$("[id$='.errors']:first").css("background-color","#FFFFCC");
     setTimeout(function(){
     $("[id$='.errors']:first").focus();
    },300);

 });
 </script> 

回答by Okan Kocyigit

I did not understand why you are trying to focus a div and what you expect, normally you can't focus a div, but you can do that like this,

我不明白你为什么要聚焦一个 div 以及你期望什么,通常你不能聚焦一个 div,但你可以这样做,

$(document).ready(function() {
$("[id$='.errors']:first").css("background-color","#FFFFCC");
     setTimeout(function(){
         $("[id$='.errors']:first").attr("tabindex",-1).focus();
         alert(document.activeElement.innerHTML+ "is focussed");
    },300);
 });??

http://jsfiddle.net/x7euD/3/

http://jsfiddle.net/x7euD/3/