找到你要的答案

Q:Override autofocus attribute with Javascript/JQuery

Q:自动对焦属性重写JavaScript/jQuery

If I have two input fields, one with the autofocus attribute and one without, how do I focus on the one without the autofocus attribute on document load? For instance:

<script type="text/javascript">
$(document).ready(function() {
    // $("input[name=\"bar\"]").blur();
    // $("input[autofocus]").removeAttr("autofocus");
    $("input[name=\"foo\"]").focus();
});
</script>
<p><input name="foo" type="text"></p>
<p><input autofocus name="bar" type="text"></p>

When I load the page, the cursor is fixed on the second input field instead of the first. I have tried the commented out lines to try and fix this somehow but I have had no success.

Edit: I have tried the solution mentioned in the "duplicate question", which was to use .blur() on the element, but that did not work. Additionally, the duplicate question only answers how to disable the autofocus and does not answer how to re-focus on another input field afterwards.

如果我有两个输入框,一个自动对焦的属性和一个不怎么关注一个没有文件加载自动对焦属性?例如:

<script type="text/javascript">
$(document).ready(function() {
    // $("input[name=\"bar\"]").blur();
    // $("input[autofocus]").removeAttr("autofocus");
    $("input[name=\"foo\"]").focus();
});
</script>
<p><input name="foo" type="text"></p>
<p><input autofocus name="bar" type="text"></p>

当我加载页面时,光标被固定在第二个输入字段上,而不是第一个。我已经尝试了评论的线试图纠正这个不知何故,但我没有成功。

Edit: I have tried the solution mentioned in the "duplicate question", which was to use .blur() on the element, but that did not work. Additionally, the duplicate question only answers how to disable the autofocus and does not answer how to re-focus on another input field afterwards.

answer1: 回答1:

After spending some more time with this, I finally figured out that 'focus' was firing too early. To solve this problem, all I had to do was wrap it in a settimeout:

setTimeout(function() {
    $("#myTags input[type=\"text\"]").focus();
}, 20);
$("input[autofocus]").blur();

在花了更多的时间,我终于发现,'焦点'发射太早。为了解决这个问题,我所要做的就是把它包在一个setTimeout:

setTimeout(function() {
    $("#myTags input[type=\"text\"]").focus();
}, 20);
$("input[autofocus]").blur();
javascript  jquery  input  autofocus