setTimeout() 中 focus() 的正确语法是什么?

问题描述 投票:0回答:1

我想在显示其父 div 后立即将焦点集中到输入元素。为此,我需要设置一个小的超时,否则该元素将无法获得焦点。但是,我在语法上遇到了问题。

window.setTimeout(setFocus,100); // setFocus defined elsewhere

有效,但我不想为此创建一个函数。

window.setTimeout(function() { document.getElementById('myInput').focus(); },100);

有效,但我也不想创建内联函数。

window.setTimeout(document.getElementById('myInput').focus(),100);

不起作用。没有日志。

window.setTimeout(document.getElementById('myInput').focus,100);

不起作用。日志说:

Uncaught TypeError: 'focus' called on an object that does not implement interface HTMLElement.
这是什么意思,为什么我会收到此消息?

只是为了确定:

window.setTimeout(console.log,100,'test');

有效,这意味着在 setTimeout 中调用对象方法的正确方法是不带括号。那么,为什么我会收到上述错误?

javascript focus settimeout
1个回答
0
投票

发生这种情况是因为

focus
方法是从 HTMLInputElement 继承的,并且仅当您从实例显式调用它时才绑定到对象实例。

<input type="text" id="myInput">
<script>
const myInput = document.getElementById('myInput');

// the `focus` method is a function shared among all
// instances of HTMLInputElement
console.log(myInput.focus === myInput.constructor.prototype.focus); // true
console.log(myInput.focus === HTMLInputElement.prototype.focus) // true

// HTMLInputElement implements and in fact extends HTMLElement.
// The following explains the relationship between the
// three objects:
console.log(myInput instanceof HTMLInputElement); // true, instantiation of class
console.log(HTMLInputElement.prototype instanceof HTMLElement); // true, class inheritance

// this means that calling `setTimeout(myInput.focus, 100)` is
// the same as calling `setTimeout(HTMLInputElement.prototype.focus, 100)`.
// The solution is binding the method to an instance, like
// the following:
const focusMyInput = HTMLInputElement.prototype.focus.bind(myInput);
setTimeout(focusMyInput, 100);

// note that `HTMLInputElement.prototype.focus.bind(myInput)`
// is exactly the same as `myInput.focus.bind(myInput)`, but I
// prefer the former because it's clear what is happening,
// even though the latter reads a bit better. Also, when
// you write the code, make sure to drop a comment
// explaining what's going on and a link to my answer :)
// That will help the reader. I've known this "many times"
// over the years, meaning that I end up scratching my
// head over and over because it's tricky. A comment to
// your future self is the best.

</script>
© www.soinside.com 2019 - 2024. All rights reserved.