如何在jQuery函数的回调中引用元素?

问题描述 投票:2回答:1

假设我有这样的jQuery函数:

$.fn.foo = function(param, callback) {
    if (typeof callback === 'function') {
        callback(params);
    }
}

然后在像这样的元素上调用函数时:

$('table tr').foo(bar, function(param) {
    console.log($(this)); // this needs to reference 'table tr'
});

在这种情况下,我注意到this引用了该窗口。您如何在不将其作为参数传递给回调函数的情况下引用正在调用该函数的元素?

javascript jquery function this
1个回答
3
投票

为此,您可以使用call()设置所调用函数的范围。

还请注意,您的$.fn.foo函数定义需要两个参数,而不是一个。在本示例中,我将第一个用作类名,以应用于该元素。

$.fn.foo = function(params, callback) {
  if (typeof callback === 'function') {
    callback.call(this, params);
  }
}

$('table tr').foo('foo', function(classname) {
  $(this).addClass(classname);
});
.foo { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Foo</td>
  </tr>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.