1

hoverIntent という jQuery プラグインが埋め込まれた単純な GreaseMonkey スクリプトを作成しています。(これは非常に小さなプラグインなので、ホストするのではなく埋め込みます。)

私の問題: プラグインがそのイベント ハンドラーを 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 固有のタグをすべて削除し、コンソールから実行すると正常に動作します。そして、これが私が埋め込んでいるプラグインです

4

1 に答える 1

1

グリースモンキー スクリプトは onDOMLoaded の前または後に実行されますか? jQueryスクリプトが親ウィンドウによって供給され、ロードされるまで、スクリプトの実行を遅らせる必要がある場合があります...

コメントごとに編集:

上記のコードに document.ready ビットが表示されませんが、それについてのコメントは表示されます...ただし、スクリプトでのコメントは少し遅すぎて使用できません...これは次のように説明できます:

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

/* some code here */セクションに何を入れても、この行unsafeWindow.jQueryが定義される前に実行された場合、未定義のオブジェクトで関数を呼び出すことになります...

unsafeWindow のGreaseSpot wiki を読むと、次の代替アプローチが提案されます。

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奇妙です。

于 2009-08-09T13:45:42.583 に答える