当我学习 JavaScript 中的“this”关键字时,我编写了一些代码:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<style>
h1 {
color:red;
}
</style>
<body>
<script>
function doSomething() {
this.style.display = 'none';
}
</script>
<div onclick="doSomething(this)">
<h1>This is a Heading</h1>
</div>
<p>This is a paragraph.</p>
</body>
</html>
但是,当我点击div时,它没有隐藏,并且控制台给出以下错误:
Uncaught TypeError: Cannot set property 'display' of undefined
我也尝试过将点击事件附加到 h1 标签,但也不起作用。知道我的代码有什么问题吗?谢谢。
最佳答案
onclick="doSomething(this)"
将调用 doSomething
,传入 this
作为参数,this
是对 div
元素的引用。
doSomething
不接受任何参数。但是,为了使其正常工作,它需要接受参数,如下所示:
function doSomething(referenceToTheElement) {
referenceToTheElement.style.display = 'none';
}
h1 {
color: red;
}
<div onclick="doSomething(this)">
<h1>This is a Heading</h1>
</div>
<p>This is a paragraph.</p>
关于使用 "this"和 "onclick"时出现 JavaScript 错误 - 无法设置未定义的属性 'display',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36298299/