javascript - 接收错误消息 : "Uncaught TypeError: Cannot read property ' focus' of null"when trying to call focus() to an element ID

标签 javascript jquery html

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

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

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

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

Uncaught TypeError: Cannot read property 'focus' of null

最佳答案

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

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

或者改用 jquery 选择器:

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

关于javascript - 接收错误消息 : "Uncaught TypeError: Cannot read property ' focus' of null"when trying to call focus() to an element ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35873277/

相关文章:

javascript - ts-node 支持 '@' 样式导入吗?如果可以的话,该如何设置呢?

javascript - Bootstrap 折叠类无法正确切换

javascript - 如何使用 onbeforeunload 事件等待 jquery 动画完成?

javascript - 使用箭头键/jQuery 浏览多个列表?

html - 可变高度列,背景颜色

html - 在自定义范围输入中显示刻度位置

html - 导航栏文本悬停/CSS 不起作用

javascript - 打开隐藏的 iframe 以在文档准备好时下载文件

javascript - Angular JS 传递 ng-repeat $index 作为参数

javascript - 如何使用导入的 JS 对象数组部署 REST API?