将 this 绑定到当前函数

binding this to the current function

我在多个函数中使用相同的元素,如下所示:

$('.edit').on('click',function(){
var elem1 = $(this).closest('tr').find('td').eq(0);
var elem2 = $(this).closest('tr').find('td').eq(1);
console.log(elem1);
});
$('.update').on('click',function(){
var elem1 = $(this).closest('tr').find('td').eq(0);
var elem2 = $(this).closest('tr').find('td').eq(1);
console.log(elem1);
});

所以,我想在函数外对我的变量进行排序,以便它们可以在多个函数中引用,如下所示:

var elem1 = $(this).closest('tr').find('td').eq(0);
var elem2 = $(this).closest('tr').find('td').eq(1);
$('.edit').on('click',function(){
console.log(elem1);
});
$('.update').on('click',function(){
console.log(elem1);
});

$(this) 不引用当前函数上下文。那么,我该如何管理呢?

this指的是method/function被调用的范围。因此,在您的示例代码中,this 实际上是全局范围(在浏览器中为 window)。

您可以将 this 作为参数传递。

var elem1 = function(ref) {
  return $(ref).closest('tr').find('td').eq(0)
};
var elem2 = function(ref) {
  return $(ref).closest('tr').find('td').eq(1);
}

$('.edit').on('click',function(){
  console.log(elem1(this));
});
$('.update').on('click',function(){
  console.log(elem1(this));
});