我有一个函数,我想执行与调用元素相关的函数,但我似乎无法将其作为对我要执行的函数的引用传递。
简而言之,这有效
<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()
函数中,this
是window
对象。
尝试将元素作为参数传递:
<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>
呵呵,吉姆