我将如何通过另一个方法来执行一个方法到原始的$(this)

How would I go about performing a method through another method to the original $(this)?

本文关键字:方法 一个 原始 this 另一个 执行 何通过      更新时间:2023-09-26

例如:

function masterMethod(this, action){
 // (action); <-- But action requires $(this) to be defined.
}
$(".item").click(function(){
  function minorMethod(){
   alert($(this));
  }
  masterMethod($(this), minorMethod)
});

我将如何执行操作并在masterMethod中传递$(this)?

您可以使用call[MDN]:

function masterMethod(element, action){
     action.call(element);
}
$(".item").click(function(){
    function minorMethod(){
        alert($(this));
    }
    masterMethod(this, minorMethod)
    // or directly here?
    // minorMethod.call(this)
});

请注意我所做的两个更改:我没有将$(this)传递给masterMethod,而是传递了this(DOM元素),因为在minorMethod内部,您将再次将this传递给jQuery。如果您正在传递$(this),那么最终将再次向jQuery传递一个jQuery对象,即$($(this)),这是不必要的。

我不确定它是否真的会引发错误,但无论如何,您都不应该将参数命名为this