我将如何通过另一种方法执行原始$(this)的方法?

时间:2012-03-31 10:33:58

标签: javascript jquery methods

例如:

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

$(".item").click(function(){
  function minorMethod(){
   alert($(this));
  }
  masterMethod($(this), minorMethod)
});

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

1 个答案:

答案 0 :(得分:3)

您可以使用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内,您正在传递{ {1}}再次使用jQuery。如果你传递this,你最终会再次将jQuery对象传递给jQuery,即$(this),这是不必要的。

我不确定它是否会引发错误,但无论如何,你不应该将你的论点命名为$($(this))