压倒一切jQuery.find()函数来提供额外的功能
问题描述:
我想重写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函数?
答
在您参考演示使用从.fn.
jQuery.fn.remove
的功能在哪里你在
jQuery.find
重写功能,在这个层面上覆盖的功能有不同的含义为this
。 当您在.fn.
上工作时 - 这是返回的查询结果,它被“混合”到任何查询结果中。
这里,this
将是根对象本身,并且通过它的使用是不同的。这些是“静态”调用的函数或实用函数。
答
你要找的覆盖/挂接到jQuery.fn.find
不jQuery.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;
};
})();
答
其实我没有看到你的代码的任何故障。这个例子使用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/
覆盖jquery.fn而不是解决了这个问题。感谢您的额外解释。 – kabaros 2011-03-17 12:02:12
我不确定你要做什么 - 所以我试图找出两种选择和他们的含义:) – 2011-03-17 14:49:46