如何使用箭头函数在更改事件上传递参数 "this"
How pass parameter "this" on change event using Arrow Function
我通常有这样的代码:
HTML 代码:
<select id="mySelectOne">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
JS代码:
$("#mySelectOne").on("change",function(){
var value = $(this).val(); // Return the value selected
alert(value);
});
使用箭头函数:
$("#mySelectTwo").on("change", () => {
var value = $(this).val(); //"this" is undefined
alert(value);
});
演示: https://jsfiddle.net/cmedina/kr1hxxtm/
当我使用箭头函数时this
的值是undefined
(应该参考select元素)。
如何传递参数?
你不能。这是箭头函数的一半,它们关闭 this
而不是根据它们的调用方式设置自己的函数。对于问题中的用例,如果您希望在调用处理程序时由 jQuery 设置 this
,则处理程序需要是 function
函数。
但是如果你有使用箭头的理由(也许你想使用 this
因为箭头外的意思),你可以使用 e.currentTarget
而不是 this
如果你喜欢:
$("#mySelectTwo").on("change", e => { // Note `e` argument
var value = $(e.currentTarget).val(); // ...and using it here
alert(value);
});
事件对象上的 currentTarget
与调用处理程序时 jQuery 设置的 this
相同。
我通常有这样的代码:
HTML 代码:
<select id="mySelectOne">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
JS代码:
$("#mySelectOne").on("change",function(){
var value = $(this).val(); // Return the value selected
alert(value);
});
使用箭头函数:
$("#mySelectTwo").on("change", () => {
var value = $(this).val(); //"this" is undefined
alert(value);
});
演示: https://jsfiddle.net/cmedina/kr1hxxtm/
当我使用箭头函数时this
的值是undefined
(应该参考select元素)。
如何传递参数?
你不能。这是箭头函数的一半,它们关闭 this
而不是根据它们的调用方式设置自己的函数。对于问题中的用例,如果您希望在调用处理程序时由 jQuery 设置 this
,则处理程序需要是 function
函数。
但是如果你有使用箭头的理由(也许你想使用 this
因为箭头外的意思),你可以使用 e.currentTarget
而不是 this
如果你喜欢:
$("#mySelectTwo").on("change", e => { // Note `e` argument
var value = $(e.currentTarget).val(); // ...and using it here
alert(value);
});
事件对象上的 currentTarget
与调用处理程序时 jQuery 设置的 this
相同。