2009-08-09 172 views
1

我正在寫一個簡單的GreaseMonkey腳本,它有一個名爲hoverIntent的jQuery插件嵌入其中。 (我嵌入它,而不是託管它,因爲它是一個非常小的插件。)在Greasemonkey腳本中使用jQuery插件

我的問題:插件將其事件處理程序附加到DOM對象後,該事件觸發一條錯誤消息,說:「jQuery未定義「。

它是一個範圍問題?這是我的整個腳本:

if(unsafeWindow.console){ 
     var GM_log = unsafeWindow.console.log; 
    } 


    (function($){ 
      //HoverIntent 
      $.fn.hoverIntent=function(f,g){...}; 
      //Removed the plugin code. You can see it in the link at the bottom 
      //of the post. 



    //DOM is ready 
    //Fetch all the rows with arrows 
    $('.arrow') 
     .each(function(){ 
      $(this).hoverIntent(mouseOver,mouseOut);    
     }); 

    //mouseOver 
    function mouseOver(){ 
     //THIS IS WHERE THE ERROR HAPPENS 
     $(this).click(); 
    } 

    //mouseOut 
    function mouseOut(){ //nothing here. 
    } 

    })(unsafeWindow.jQuery); 

它工作正常,當我複製粘貼它,刪除所有GM特定標籤,並從我的控制檯運行它。和this is the plugin I am embedding

回答

1

在onDOMLoaded之前或之後運行greasemonkey腳本嗎?您可能需要延遲執行腳本的執行,直到後jQuery腳本是由父窗口來源,並加載...根據註釋

編輯:

我沒有看到的document.ready位你上面的代碼,雖然我看到你關於它的評論。不過,您的評論是有點腳本太晚而沒有任何用途...這也許可以解釋:

(function($){ /* some code here */ })(unsafeWindow.jQuery) 

不管你放什麼的/* some code here */部分,如果在定義unsafeWindow.jQuery之前執行該行,則仍然會調用未定義對象上的函數的...

GreaseSpot wiki on unsafeWindow,它建議的替代方法:

var script = document.createElement("script"); 
script.type = "application/javascript"; 
script.innerHTML = "(function($){ 
     //HoverIntent 
     $.fn.hoverIntent=function(f,g){...}; 
     //Removed the plugin code. You can see it in the link at the bottom 
     //of the post. 



    //DOM is ready 
    //Fetch all the rows with arrows 
    $('.arrow') 
     .each(function(){ 
       $(this).hoverIntent(mouseOver,mouseOut);     
     }); 

    //mouseOver 
    function mouseOver(){ 
     //THIS IS WHERE THE ERROR HAPPENS 
     $(this).click(); 
    } 

    //mouseOut 
    function mouseOut(){ //nothing here. 
    } 

})(jQuery);"; 

document.body.appendChild(script); 

編輯:沒有我的答案一定是有意義的,雖然,因爲你使用的$對象的幾行在發行之前呈現自己..:-S怪異。

+0

好問題。我的理解是userscripts在加載DOM後加載,但爲了安全起見,我在腳本中使用了一個文檔,就像你上面看到的那樣。 – picardo 2009-08-09 15:07:37

相關問題