我正在尝试在 Firefox 扩展中使用 jQuery,并且实际上想使用 jQuery 来操作当前页面的 DOM,而不是 XUL 文件的上下文。因此,我在 XUL 文件中加载 jQuery,并将其传递给沙箱中的一些脚本(使用 Greasemonkey 扩展编译器 http://arantius.com/misc/greasemonkey/script-compiler)。由于 jQuery 未随页面 DOM 一起加载,因此我想将其选择器上下文设置为页面 DOM,而不是总是将其传递到 jQuery 调用中。
我按照 How to use jQuery in Firefox Extension 中的解决方案进行操作几乎达到了我想要的。
jQuery.noConflict();
$ = function(selector,context){ return new jQuery.fn.init(selector,context||example.doc); };
$.fn = $.prototype = jQuery.fn;
我能够调用 jQuery() 函数,并且页面 DOM 将用作上下文。但是,我不能使用像 jQuery.trim 这样的函数,因为这些函数没有定义。
我认为解决方案中的这一行
$.fn = $.prototype = jQuery.fn;
会让我自己的 jQuery 对象继承所有 jQuery 原型属性,但显然没有。
给定一个普通的 jQuery 对象,如何重新定义它以使用某个元素作为选择器上下文,同时保留所有 jQuery 函数?
I'm trying to use jQuery inside a Firefox extension, and actually want to use jQuery to manipulate the DOM of the current page, as opposed to the context of the XUL file. Thus, I load jQuery in my XUL file, and pass it to some of my scripts in a sandbox (using the Greasemonkey extension compiler http://arantius.com/misc/greasemonkey/script-compiler). Since jQuery was not loaded with the page DOM, I want to set its selector context to the page DOM instead of always passing it into jQuery calls.
I followed the solution at How to use jQuery in Firefox Extension and it almost achieves what I want.
jQuery.noConflict();
$ = function(selector,context){ return new jQuery.fn.init(selector,context||example.doc); };
$.fn = $.prototype = jQuery.fn;
I'm able to make calls to the jQuery() function, and the page DOM will be used as the context. However, I can't use functions like jQuery.trim as those are not defined.
I thought this line from the solution
$.fn = $.prototype = jQuery.fn;
will let my own jQuery object inherit all of the jQuery prototype properties, but it apparently doesn't.
Give a vanilla jQuery object, how do I redefine it to use a certain element as the selector context, while preserving all jQuery functions?
发布评论
评论(3)
.trim()、.ajax() 等是静态方法,这意味着它们绑定到 jQuery 构造函数而不是它的原型。
然而,一个也许不错的方法是保持 jQuery 不变并执行以下操作:
这也是一种优化,因为不必再为每个查询手动设置上下文。
.trim(), .ajax() etc are static methods, meaning they are bound to the jQuery constructor and not it's prototype.
However a perhaps nice way is to leave jQuery intact and do the following:
This is also an optimisation since the context doesnt have to be manually set anymore with each query.
另一种方法是重写构造函数:
Another way of doing it is overriding the constructor: