pmc*_*255 17 javascript jquery dom greasemonkey firefox-addon
我正在尝试在Firefox扩展中使用jQuery,并且实际上想要使用jQuery来操作当前页面的DOM,而不是XUL文件的上下文.因此,我在我的XUL文件中加载jQuery,并将其传递给沙盒中的一些脚本(使用Greasemonkey扩展编译器http://arantius.com/misc/greasemonkey/script-compiler).由于jQuery没有加载页面DOM,我想将其选择器上下文设置为页面DOM,而不是总是将其传递给jQuery调用.
我按照如何在Firefox扩展中使用jQuery的解决方案,它几乎实现了我想要的.
jQuery.noConflict();
$ = function(selector,context){ return new jQuery.fn.init(selector,context||example.doc); };
$.fn = $.prototype = jQuery.fn;
Run Code Online (Sandbox Code Playgroud)
我可以调用jQuery()函数,页面DOM将用作上下文.但是,我不能使用像jQuery.trim这样的函数,因为它们没有定义.
我从解决方案中想到了这一点
$.fn = $.prototype = jQuery.fn;
Run Code Online (Sandbox Code Playgroud)
将让我自己的jQuery对象继承所有jQuery原型属性,但显然不会.
给一个vanilla jQuery对象,如何重新定义它以使用某个元素作为选择器上下文,同时保留所有jQuery函数?
BGe*_*sen 11
.trim(),. ajax()等是静态方法,这意味着它们绑定到jQuery构造函数而不是它的原型.
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 $
Run Code Online (Sandbox Code Playgroud)
然而,一个可能很好的方法是保持jQuery完整并执行以下操作:
var fromDoc = $(document);
// and if you want to find stuff:
fromDoc.find('div').doSomething();
fromDoc.find('.someClass').doSomethingElse();
Run Code Online (Sandbox Code Playgroud)
这也是一种优化,因为不必为每个查询手动设置上下文.
| 归档时间: |
|
| 查看次数: |
4430 次 |
| 最近记录: |