2012-12-04 27 views
2

我已閱讀關於此問題的許多帖子,並嘗試了所有包含jQuery的方式。jQuery在Firefox擴展中與全局命名空間中沒有衝突

如果我在xul文件中加載jQuery並將其存儲在一個變量中,它就起作用。 (如How to use jQuery in Firefox Extension

jQuery.noConflict(); 
sbsh.safeWalletUtils.$ = function (selector, context) { 
    return new jQuery.fn.init(selector, context || doc); 
}; 
sbsh.safeWalletUtils.$.fn = sbsh.safeWalletUtils.$.prototype = jQuery.fn; 

不過,我懷疑這裏的建議的解決方案要好得多: http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087

loadjQuery: function(wnd){ 
    var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] 
.getService(Components.interfaces.mozIJSSubScriptLoader); 
    loader.loadSubScript("chrome://clhelper/content/jquery/jquery-1.5.js",wnd); 
    var jQuery = wnd.jQuery.noConflict(true); 
    loader.loadSubScript("chrome://clhelper/content/jquery/jquery.hoverIntent.js", jQuery); 
    return jQuery; 
}, 

在頁面加載事件處理程序:

var doc = event.originalTarget; 
var wnd = doc.defaultView; 
// load jQuery and save it as a property of the window 
myprivatejQuery = loadjQuery(wnd) 

不過我不斷得到wnd.jQuery undefined ..(鏈接中的幾個人也表示這是問題)

我該怎麼辦? 如何使用jQuery而不用擔心Firefox擴展中的衝突?

+0

我沒有你的問題的答案,但你應該檢查'$'或'jQuery'變量是否已經命名空間,然後再執行上述任何操作。 – Ohgodwhy

+0

是的,但這也可能意味着它是一箇舊版本..不管怎麼說,我必須再試驗一下.. –

回答

1

更多的調查後,並感謝卡斯堡盟爲他不懈的工作..

我們現在明白爲什麼我們得到的錯誤。

做正確的做法是不是在XUL文件作爲包括(我懷疑),但通過調用展開JS對象:

// correct function to load jQuery 
var loadjQuery = function(wnd){ 
    var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"] 
    .getService(Components.interfaces.mozIJSSubScriptLoader); 
    loader.loadSubScript("chrome://sbshsafewallet/content/jquery-1.8.3.js", wnd); 
    var jQuery = XPCNativeWrapper.unwrap(wnd).$; 
    jQuery.noConflict(true); 
    return jQuery; 
}; 


// field to store the jQuery for the current document window (as there can be multiple tabs) 
var jQueryForWindow = null; 

// event to call on window load (didn't include the code, left for reader to do) 
windowLoad = function (event) 
{ 
    var appcontent = document.getElementById("appcontent"); // browser 
    appcontent.addEventListener("DOMContentLoaded", pageLoadedInit, false); 
} 

// load jQuery on DOMContentLoaded event 
pageLoad = function (event) { 
     var doc = event.originalTarget; 
     var wnd = doc.defaultView; 
     jQueryForWindow = loadjQuery(wnd); 
} 


//example of function using the jQuery 
function usesjQuery() 
{ 
    var $ = jQueryForWindow; 
    //do something with jquery here 
} 

希望這有助於大家已經卡住! !

再次感謝Omri堡盟!