我有一个想要执行与调用元素相关的函数,但我似乎无法将其本身作为对我想要执行的函数的引用传递。
简而言之,这有效
<div style="background-color:#444444">
<button onclick="this.parentElement.style.display = 'none';">close</button>
</div>
这并不
<script>
function close() { this.parentElement.style.display = 'none'; }
</script>
<div style="background-color:#444444">
<button onclick="close()">close</button>
</div>
这是为什么?有解决办法吗?
最佳答案
没关系,我是个白痴
看来我可以简单地将元素传递给带有 this 关键字的函数
<script>
function close(object) { object.parentElement.style.display = 'none'; }
</script>
<div style="background-color:#444444">
<button onclick="close(this)">close</button>
</div>
关于JavaScript 函数通过调用 Element 访问 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901254/