Javascript 接收错误消息:尝试将 focus() 调用到元素 ID 时,“未捕获的类型错误:无法读取 null 的属性‘焦点’”

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

Receiving Error Message: "Uncaught TypeError: Cannot read property 'focus' of null" when trying to call focus() to an element ID

javascriptjqueryhtml

提问by Kode_12

I have an element in my DOM where I have attached an ID. I want to call focus on that element after the Page Loads and set it to a css style (border: yellow) to highlight that it's currently focused. This is what I have:

我的 DOM 中有一个元素,我在其中附加了一个 ID。我想在页面加载后调用该元素的焦点并将其设置为 css 样式(边框:黄色)以突出显示它当前处于焦点状态。这就是我所拥有的:

//main.html
  <myElement id= 'myEl'>

//main.js
window.setTimeout(function ()  { 
        document.getElementById('#myEl').focus(); 
    }, 0);

When I refresh the page I receive this error:

当我刷新页面时,我收到此错误:

Uncaught TypeError: Cannot read property 'focus' of null

未捕获的类型错误:无法读取 null 的属性“焦点”

回答by Zakaria Acharki

That because javascript can't find any element with id='#myEl', remove the extra #in :

那是因为 javascript 找不到任何带有 的元素id='#myEl',删除额外的#in :

document.getElementById('#myEl').focus(); 
_________________________^

Or use jquery selector instead :

或者改用 jquery 选择器:

$('#myEl').focus(); 

Hope this helps.

希望这可以帮助。

回答by mrbengi

Component ID changes in runtime, so use a class rather than ID, will work, like

组件 ID 在运行时更改,因此使用类而不是 ID 会起作用,例如

$(".ClassName").focus();

回答by devhelp37

Below working code for example reference

下面的工作代码作为示例参考

template code

模板代码

<div class="css-description">description</div>

script code

脚本代码

this.$nextTick(() => {
   $(".css-description").focus();
})