如何在箭头函数中使用 'this' 来引用被单击的元素
How to use 'this' in an arrow function for referencing the clicked element
HTML
<div class="sym-box" data-card="0">
<div id="a"><img src="..."></div>
</div>
<div class="sym-box" data-card="1">
<div id="b"><img src="..."></div>
</div>
<div class="sym-box" data-card="2">
<div id="c"><img src="..."></div>
</div>
JS
var attribute;
function myFunction() {
attribute = this.getAttribute('data-card');
}
var symboxes = document.getElementsByClassName('sym-box');
for (i = 0; i < symboxes.length; i++) {
symboxes[i].addEventListener('click', myFunction, false);
}
上面的代码按预期工作,'this' 引用了单击的元素。但是,当我将它写成箭头函数时,我得到 "Uncaught TypeError: this.getAttribute is not a function" 因为 'this' 现在指的是 window 对象。
const myFunction = () => {
attribute = this.getAttribute('data-card');
};
所以我的问题是如何将 myFunction() 重写为箭头函数,其中 'this' 指的是被点击的元素?
注意:
我的问题已被标记为重复问题,但我要求在使用箭头函数时解决同样的问题。只是被告知 "You can't" 或 "Don't" 并没有回答我的问题。
So my question is how do I rewrite myFunction() as an arrow function
where 'this' refers to the clicked element?
将myFunction
定义为arrow-function,this
指的是定义它的范围.
使用event.target
(如果您仍想使用箭头函数)
const myFunction = (event) => {
attribute = event.currentTarget.getAttribute('data-card');
};
您不能覆盖箭头函数的 this
值。该箭头函数的 this
值将从其执行上下文中获取。一旦绑定,就不能被替换或覆盖。这是基本规则。
const myFunction = () => {
attribute = this.getAttribute('data-card');
};
所以在您的代码中,myFunction 变量声明范围内可用的 this
值将被获取并绑定到函数。这里的经验法则是,不要 对事件侦听器使用箭头函数。
您可以阅读有关箭头函数的更多信息 here。
HTML
<div class="sym-box" data-card="0">
<div id="a"><img src="..."></div>
</div>
<div class="sym-box" data-card="1">
<div id="b"><img src="..."></div>
</div>
<div class="sym-box" data-card="2">
<div id="c"><img src="..."></div>
</div>
JS
var attribute;
function myFunction() {
attribute = this.getAttribute('data-card');
}
var symboxes = document.getElementsByClassName('sym-box');
for (i = 0; i < symboxes.length; i++) {
symboxes[i].addEventListener('click', myFunction, false);
}
上面的代码按预期工作,'this' 引用了单击的元素。但是,当我将它写成箭头函数时,我得到 "Uncaught TypeError: this.getAttribute is not a function" 因为 'this' 现在指的是 window 对象。
const myFunction = () => {
attribute = this.getAttribute('data-card');
};
所以我的问题是如何将 myFunction() 重写为箭头函数,其中 'this' 指的是被点击的元素?
注意: 我的问题已被标记为重复问题,但我要求在使用箭头函数时解决同样的问题。只是被告知 "You can't" 或 "Don't" 并没有回答我的问题。
So my question is how do I rewrite myFunction() as an arrow function where 'this' refers to the clicked element?
将myFunction
定义为arrow-function,this
指的是定义它的范围.
使用event.target
(如果您仍想使用箭头函数)
const myFunction = (event) => {
attribute = event.currentTarget.getAttribute('data-card');
};
您不能覆盖箭头函数的 this
值。该箭头函数的 this
值将从其执行上下文中获取。一旦绑定,就不能被替换或覆盖。这是基本规则。
const myFunction = () => {
attribute = this.getAttribute('data-card');
};
所以在您的代码中,myFunction 变量声明范围内可用的 this
值将被获取并绑定到函数。这里的经验法则是,不要 对事件侦听器使用箭头函数。
您可以阅读有关箭头函数的更多信息 here。