在Greasemonkey脚本中使用jQuery插件
我正在编写一个简单的GreaseMonkey脚本,其中嵌入了一个名为hoverIntent的jQuery插件。(我嵌入它而不是托管它,因为它是一个非常小的插件。) 我的问题是:插件将其事件处理程序附加到DOM对象后,该事件会触发一条错误消息,提示:“jQuery未定义。” 这是一个范围问题吗?以下是我的整个脚本:在Greasemonkey脚本中使用jQuery插件,jquery,greasemonkey,Jquery,Greasemonkey,我正在编写一个简单的GreaseMonkey脚本,其中嵌入了一个名为hoverIntent的jQuery插件。(我嵌入它而不是托管它,因为它是一个非常小的插件。) 我的问题是:插件将其事件处理程序附加到DOM对象后,该事件会触发一条错误消息,提示:“jQuery未定义。” 这是一个范围问题吗?以下是我的整个脚本: if(unsafeWindow.console){ var GM_log = unsafeWindow.console.log; } (func
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特定的标签,并从我的控制台运行它时,它工作正常。和 greasemonkey脚本是在onDOMLoaded之前还是之后运行的?您可能需要延迟脚本的执行,直到父窗口获取jQuery脚本并加载该脚本之后 按评论编辑: 我没有看到上面代码中的document.ready位,尽管我看到了您对它的评论。。。然而,你的评论在脚本中有点太晚了,没有任何用处。。。这或许可以解释:
(function($){ /* some code here */ })(unsafeWindow.jQuery)
无论您在/*此处的某些代码*/
部分中放置了什么,如果在定义unsafeWindow.jQuery
之前执行这一行,您仍将调用未定义对象上的函数
通过阅读,它提出了以下替代方法:
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);
编辑:不过,我的答案没有一个是有意义的,因为在问题出现之前,您在几行中使用了
$
对象-这很奇怪。greasemonkey脚本是在onDOMLoaded之前还是之后运行的?您可能需要延迟脚本的执行,直到父窗口获取jQuery脚本并加载该脚本之后
按评论编辑:
我没有看到上面代码中的document.ready位,尽管我看到了您对它的评论。。。然而,你的评论在脚本中有点太晚了,没有任何用处。。。这或许可以解释:
(function($){ /* some code here */ })(unsafeWindow.jQuery)
无论您在/*此处的某些代码*/
部分中放置了什么,如果在定义unsafeWindow.jQuery
之前执行这一行,您仍将调用未定义对象上的函数
通过阅读,它提出了以下替代方法:
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);
编辑:不过,我的答案没有一个是有意义的,因为在问题出现之前,您在几行中使用了
$
对象-这很奇怪。问得好。我的理解是,用户脚本是在DOM加载之后加载的,但为了安全起见,我在脚本中使用了一个文档,正如您在上面看到的。问得好。我的理解是,用户脚本是在加载DOM之后加载的,但为了安全起见,我在脚本中使用了一个文档,正如您在上面看到的那样。