Override default jQuery selector context

断了今生、忘了曾经 提交于 2019-11-28 09:05:25

.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.

var jQueryInit = $.fn.init;

$.fn.init = function(arg1, arg2, rootjQuery){
    arg2 = arg2 || window.document;
    return new jQueryInit(arg1, arg2, rootjQuery);
};

Another way of doing it is overriding the constructor:

var initjQuery = jQuery.fn.init;
$.fn.init = function(s,c,r) {
    c = c || window.document;
    return new initjQuery(s,c,r);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!