JavaScript 函数 通过调用 Element 访问此内容

JavaScript Function Access this from calling Element

本文关键字:访问 Element 调用 函数 JavaScript      更新时间:2023-09-26

我有一个函数,我想执行与调用元素相关的函数,但我似乎无法将其作为对我要执行的函数的引用传递。

简而言之,这有效

<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>

这是因为在close()函数中,thiswindow对象。

尝试将元素作为参数传递:

<script>
    function close(btn) { btn.parentElement.style.display = 'none'; }
</script>
<div style="background-color:#444444">
    <button onclick="close(this)">close</button>
</div>

在我的头顶上,"this"并不指向函数中的同一对象,因为它在内联代码中指向相同的对象。 您可以在函数调用中传递"this",如下所示:

<script>
   function close(whichObj) { whichObj.parentElement.style.display = 'none'; }
</script>
<div style="background-color:#444444">
    <button onclick="close(this)">close</button>

呵呵,吉姆