Javascript如何将此关键字传递给函数?

问题描述 投票:0回答:2

大家好,我想通过按钮轻松修改jajaja来修改属性

document.getElementById("button_1").style.visibility = "collapse";

但是我在这里有想要更改的对象的ID,但是如果我不特别知道ID,因为该对象来自循环,我应该使用JavaScript关键字“ this”对吗?像“ this.id”一样进入它所调用的对象的ID

<input type='button' id='button_1' onclick='alert(this.id)' >Click Me!</button>

将显示该元素的ID

当我调用函数时

<script>
function Funtion_Alert() {

    alert (this.id);

}
</script>

<input type='button' id='button_1' onclick='Funtion_Alert(this)' >Click Me!</button>

我进入y警报未定义状态,我需要从调用函数的元素中获取ID

javascript properties this element
2个回答
0
投票

这不是您通过this的方式。 this很特殊,它是当前函数调用的上下文。

Either将其作为参数传递,但是随后您必须在函数内部调用它,例如:

<script>
function Funtion_Alert(element) { // <<< note the argument!

    alert(element.id); // <<< note the different name!

}
</script>

<input type='button' id='button_1' onclick='Funtion_Alert(this)' >Click Me!</button>

... 通过使用this将其作为实际的Function.prototype.call传递:

Function.prototype.call

否则,函数内的<script> function Funtion_Alert() { alert(this.id); } </script> <input type='button' id='button_1' onclick='Funtion_Alert.call(this)' >Click Me!</button> <!-- note the .call --> 将是this window,因此as explained here本质上将是this.id,这不是您想要的。


0
投票

您也正在启动window.id标记,然后以input结束。

实现您要寻找的内容的一种更惯用的方法是将button移至元素:

addEventListener
addEventListener
© www.soinside.com 2019 - 2024. All rights reserved.