簡體   English   中英

我將如何通過另一個方法對原始$(this)執行一個方法?

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

例如 :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM