我已经将一个小脚本放在一起作为一个更大的测验项目的一部分,并且正在努力理解为什么在调用函数之前在函数中设置 this
关键字。这是我的代码:
$(document).ready(function ($) {
function nextCard() {
console.log('yes');
$(this).closest('.card').hide();
$(this).parent().next().show();
}
$("#start").on('click', function (e) {
e.preventDefault();
//First card to appear
nextCard();
});
$("#next").on('click', function (e) {
e.preventDefault();
nextCard();
});
});
例如,为什么不将“this”设置为元素#start?
最佳答案
在 nextCard()
中,this
将引用 window
,因为这是默认范围。因此,您的 DOM 遍历方法很可能没有像您期望的那样工作。
假设您希望函数中的 this
引用单击的 #start
或 #next
元素,您可以提供 nextCard()
的引用 到事件处理程序方法,如下所示:
$(function($) {
function nextCard(e) {
e.preventDefault();
console.log('yes');
$(this).closest('.card').hide();
$(this).parent().next().show();
}
$("#start, #next").on('click', nextCard);
});
关于javascript - 可重用函数中的“this”绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45218962/