Override default jQuery selector context

后端 未结 3 879
野趣味
野趣味 2020-12-09 17:10

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

3条回答
  •  有刺的猬
    2020-12-09 17:54

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

提交回复
热议问题