Javascript 如何将此关键字传递给函数?
Javascript How pass this Keyword to a Function?
大家好,我想修改一个 属性 从一个按钮轻松 right jajaja
document.getElementById("button_1").style.visibility = "collapse";
但是这里我有我想要更改的对象的 ID,但是如果我不知道具体的 ID,因为该对象来自一个循环,我应该使用 "this" JavaScript关键字对吗?喜欢 "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>
我收到未定义的警报我需要从正在调用该函数的元素中获取 ID
这不是你通过 this
的方式。 this
比较特殊,它是你当前函数调用的上下文。
要么将它作为参数传递,但是你必须在函数内部调用它,就像这里:
<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>
... 或 通过使用 Function.prototype.call
:
作为实际 this
传递
<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
本质上将是 window.id
,这不是您想要的。
您还开始了一个 input
标签,然后以 button
结束。
实现您正在寻找的更惯用的方法是 addEventListener
元素:
let button = document.getElementById("button_1");
button.addEventListener("click", (e) => alert(e.target.id));
<button id="button_1">Click Me!</button>
大家好,我想修改一个 属性 从一个按钮轻松 right jajaja
document.getElementById("button_1").style.visibility = "collapse";
但是这里我有我想要更改的对象的 ID,但是如果我不知道具体的 ID,因为该对象来自一个循环,我应该使用 "this" JavaScript关键字对吗?喜欢 "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>
我收到未定义的警报我需要从正在调用该函数的元素中获取 ID
这不是你通过 this
的方式。 this
比较特殊,它是你当前函数调用的上下文。
要么将它作为参数传递,但是你必须在函数内部调用它,就像这里:
<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>
... 或 通过使用 Function.prototype.call
:
this
传递
<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
本质上将是 window.id
,这不是您想要的。
您还开始了一个 input
标签,然后以 button
结束。
实现您正在寻找的更惯用的方法是 addEventListener
元素:
let button = document.getElementById("button_1");
button.addEventListener("click", (e) => alert(e.target.id));
<button id="button_1">Click Me!</button>