2011-03-16 42 views
3

我想重寫jQuery.find覆蓋額外的功能。我已經使用在本納德爾的博客這樣做(http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm)討論的想法,但由於某種原因,它不爲$ .find()工作,這是我的代碼壓倒一切jQuery.find()函數來提供額外的功能

 (function() { 
     // Store a reference to the original remove method. 
     var originalFindFunction = jQuery.find; 

     // Define overriding method. 
     jQuery.find = function() { 
      // Log that we are calling the overridden function. 
      Console.log("------> Find method called"); 

      // then execute the original method 
      var results = originalFindFunction.apply(this, arguments); 
      return results; 
     }; 
    })(); 

你有一個想法,什麼是錯的,或者我怎麼能重寫一個jquery函數?

回答

1

在您參考演示使用從.fn.

jQuery.fn.remove 

的功能在哪裏你在

jQuery.find 

重寫功能,在這個層面上覆蓋的功能有不同的含義爲this。 當您在.fn.上工作時 - 這是返回的查詢結果,它被「混合」到任何查詢結果中。

這裏,this將是根對象本身,並且通過它的使用是不同的。這些是「靜態」調用的函數或實用函數。

+0

覆蓋jquery.fn而不是解決了這個問題。感謝您的額外解釋。 – kabaros 2011-03-17 12:02:12

+0

我不確定你要做什麼 - 所以我試圖找出兩種選擇和他們的含義:) – 2011-03-17 14:49:46

1

你要找的覆蓋/掛接到jQuery.fn.findjQuery.find


(function() { 
    // Store a reference to the original remove method. 
    var originalFindFunction = jQuery.fn.find; 

    // Define overriding method. 
    jQuery.fn.find = function() { 
     // Log that we are calling the overridden function. 
     Console.log("------> Find method called"); 

     // then execute the original method 
     var results = originalFindFunction.apply(this, arguments); 
     return results; 
    }; 
})(); 
0

其實我沒有看到你的代碼的任何故障。這個例子使用jQuery原型(「fn」),不過你也可以操作$ .find。我基本上是複製你在下面的例子中所提供的相同代碼:

var oldFind = $.find; 

$.find = function() { 
    console.log("something new."); 

    console.log(oldFind.apply(this, arguments)); 
}; 

$.find("div"); 

實現,你可以以特定的方式來執行這個。你上面有:

(function() {...})(); 

這使得第一括號中的代碼,自動執行(糾正我,如果我錯了這裏),它可能沒有意圖想要的,如果你調用代碼包含這個功能之外。上面的代碼片段的一個工作例子是在這裏:http://jsfiddle.net/nuPLV/