我正在编写一个简单的GreaseMonkey脚本,其中嵌入了一个名为hoverIntent的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。
答案 0 :(得分: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);
编辑:我的答案中没有一个必然有意义,因为你在问题出现之前将$
对象用于几行......: - 很奇怪。