大家好,我想通过按钮轻松修改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
这不是您通过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
,这不是您想要的。