jQuery 将焦点设置为动态加载的 DIV 中的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1433742/
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-08-26 11:26:50  来源:igfitidea点击:

Set focus to field in dynamically loaded DIV

jqueryhtmlfocussetfocus

提问by MrG

What is the proper method to set the focus to a specific field within a dynamically loaded DIV?

将焦点设置到动态加载的 DIV 中的特定字段的正确方法是什么?

$("#display").load("?control=msgs"); // loads the HTML into the DIV
$('#display').fadeIn("fast"); // display it
$("tex#header").focus();          // ?? neither that
$("input#header").focus();        // ?? nor that
$('#display', '#header').focus()  // ?? nor that
$("#header").focus();             // ?? nor that works

The following HTML is fetched into the displayDIV:

以下 HTML 被提取到displayDIV 中:

<div id="display">
<form id="newHeaderForm" class="dataform" action="/" method="post">
    <input id="to" type="hidden" value="22" name="to"/>
    <dl>
        <dt>Header</dt>
        <dd>
            <input id="header" class="large" type="text" name="header" value="" maxlength="128"/>
        </dd>
 </form>
 </div>

Many, many thanks!

非常感谢!

回答by Jan Willem B

The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

load() 函数是一个异步函数。您应该在 load() 调用完成后设置焦点,即在 load() 的回调函数中,否则您通过 #header 引用的元素尚不存在。例如:

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
}); 

I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.

即使使用这个解决方案,我自己也遇到了问题,所以我在回调中设置了一个 setTimeout 并在超时中设置焦点以确保/真正/确保该元素存在。

回答by Paul Suart

Have you tried simply selecting by Id?

您是否尝试过简单地按 Id 选择?

$("#header").focus();

Seeing as Ids should be unique, there's no need to have a more specific selector.

由于 Id 应该是唯一的,因此不需要有更具体的选择器。

回答by Arta

Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.

是的,当操作一个尚不存在的元素时会发生这种情况(这里的一些贡献者也对唯一 ID 提出了很好的观点)。我遇到了类似的问题。我还需要将参数传递给操作即将呈现的元素的函数。

The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - closures.

此处检查的解决方案对我没有帮助。最后,我找到了一个开箱即用的工具。而且它也非常漂亮——闭包。

Instead of:

代替:

$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );

Try this:

尝试这个:

setTimeout( function() { $( '#header' ).focus() }, 500 );

In my code, testing passing the argument, this didn't work, the timeout was ignored:

在我的代码中,测试传递参数,这不起作用,超时被忽略:

setTimeout( alert( 'Hello, '+name ), 1000 );

This works, the timeout ticks:

这有效,超时滴答声:

setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );

It sucks that w3schools doesn't mention it.

w3schools 没有提到它很糟糕。

Credits go to: makemineatriple.com.

积分去:makemineatriple.com

Hopefully, this helps somebody who comes here.

希望这对来到这里的人有所帮助。

Martas

玛塔斯

回答by Bela

If

如果

$("#header").focus();

is not working then is there another element on your page with the id of header?

不工作,那么您的页面上是否还有另一个元素的标题为 id?

Use firebug to run $("#header")and see what it returns.

使用 firebug 运行$("#header")并查看它返回的内容。

回答by xman

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
});

i tried it but it doesn't work, please give me more advice to resolve this problem. thanks for your help

我试过了,但它不起作用,请给我更多的建议来解决这个问题。感谢您的帮助

回答by Per Lindberg

As Omu pointed out, you must set the focus in a document ready function. jQuery provides it for you. And do select on an id. For example, if you have a login page:

正如 Omu 所指出的,您必须在文档就绪功能中设置焦点。jQuery 为您提供了它。并选择一个 id。例如,如果您有一个登录页面:

$(function() { $("#login-user-name").focus(); }); // jQuery rocks!

回答by Doomsknight

This runs on page load.

这在页面加载时运行。

<script type="text/javascript">
    $(function () {
        $("#header").focus();
    });
</script>

回答by BCnuckles

Dynamically added items have to be added to the DOM... clone().append()adds it to the DOM... which allows it to be selected via jquery.

动态添加的项目必须添加到 DOM 中……clone().append()将其添加到 DOM 中……这允许通过 jquery 选择它。

回答by ashu

$("#header").attr('tabindex', -1).focus();

回答by skinny

$(function (){
    $('body').on('keypress','.sobitie_snses input',function(e){
        if(e.keyCode==13){
            $(this).blur();
            var new_fild =  $(this).clone().val('');
            $(this).parent().append(new_fild);
            $(new_fild).focus();
        }
    });
});

most of error are because U use wrong object to set the prorepty or function. Use console.log(new_fild); to see to what object U try to set the prorepty or function.

大多数错误是因为您使用错误的对象来设置属性或功能。使用 console.log(new_fild); 查看 U 尝试设置属性或功能的对象。