javascript - 即使在等待网页加载时也未捕获类型错误
问题描述
将 JavaScript 加载到我的网页时出现此错误
未捕获的类型错误:无法将属性“contentEditable”设置为 null
但是,在执行此操作之前,我正在等待网页加载,因此我看不出错误的原因。
JavaScript:
window.onload = (function () {
var doc = document.getElementById('doc');
doc.contentEditable = true;
doc.focus();
})();
HTML 片段:
<body>
<header class="header">
<h1 class="header__h1">editor</h1>
</header>
<div class="doc">
<div class="doc__background-ribbon"></div>
<div class="doc__text-editor hidden"></div>
</div>
<script src="myfilehereexample"></script>
</body>
解决方案
您没有带有id
of的元素doc
。它有一个class
所以.getElementById
是行不通的。将其更改为具有id
或更改查询以搜索类(如下所示):
window.onload = (function () {
var doc = document.querySelector('.doc'); // Query for the first element with a class of "doc"
doc.contentEditable = true;
doc.focus();
})();
<header class="header">
<h1 class="header__h1">editor</h1>
</header>
<div class="doc">Type here
<div class="doc__background-ribbon"></div>
<div class="doc__text-editor hidden"></div>
</div>
推荐阅读
- assembly - 从 GP regs 加载 xmm
- c# - .Net Core 为不同的构建配置启动
- atmelstudio - AtmelStudio7:MPLABCOMM_INVALID_HANDLE
- ios - 开发者如何在 ios 上找到使用应用组提供共享数据的第三方公司?
- login - Moodle 无法登录到我的 localhost/moodle
- graphql - ApolloGraphQL -- ReadQuery `Field Not Found` 错误?
- ruby - 如何将 aviglitch 脚本应用于文件夹中的每个文件?
- java - 错误:表达式的非法开头后跟 PriorityQueue
- assembly - MARIE 计算器未按预期工作
- aws-codebuild - 如何在 AWS CodeBuild 构建中使用 python boto3?