Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - Override default jQuery selector context

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.trim(), .ajax() etc are static methods, meaning they are bound to the jQuery constructor and not it's prototype.

jQuery.noConflict();
$ = function(selector,context){ return new jQuery.fn.init(selector,context||example.doc); };
$.fn = $.prototype = jQuery.fn;
jQuery.extend($, jQuery); // copy's trim, extend etc to $

However a perhaps nice way is to leave jQuery intact and do the following:

var fromDoc = $(document);
// and if you want to find stuff:
fromDoc.find('div').doSomething();
fromDoc.find('.someClass').doSomethingElse();

This is also an optimisation since the context doesnt have to be manually set anymore with each query.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...