首页 > 解决方案 > 使用“document.querySelector”时出现“未捕获的 TypeError:非法调用”

问题描述

我有这个简单的两行 JS 代码,它不断出错,并出现“未捕获的类型错误:非法调用”。

const $ = document.querySelector;
$('#someElementId').display = 'none';
<p id="someElementId">The element</p>

标签: javascript

解决方案


你错过了style财产。

使用以下代码:

$('#someElementId').style.display='none';

并且要修复,如@philIllegal Invocation的评论中所述并在此答案中发布,您必须确保将您绑定到文档:querySelector

const $ = document.querySelector.bind(document);

这是一个最终工作的片段:

const $ = document.querySelector.bind( document );
$('#someElementId').style.display = 'none';
<p id="someElementId">The element</p>


推荐阅读