如何在Greasemonkey Javascript脚本中使用jQuery?

如何在Greasemonkey Javascript脚本中使用jQuery?,javascript,jquery,greasemonkey,Javascript,Jquery,Greasemonkey,我在这里看到了一个问题和许多关于将jquery引入greasemonkey的博客文章,但我什么都做不到 这是我的剧本: // ==UserScript== // @name Hello jQuery // @namespace http://foo.bar // @description jQuery test script // @include * // ==/UserScript== #{contents of jquery.latest.js

我在这里看到了一个问题和许多关于将jquery引入greasemonkey的博客文章,但我什么都做不到

这是我的剧本:

// ==UserScript==
// @name          Hello jQuery
// @namespace     http://foo.bar
// @description   jQuery test script
// @include       *
// ==/UserScript==

#{contents of jquery.latest.js pasted in}

unsafeWindow.jQuery = jQuery;

$(document).ready(function() {
    alert('Hello world!');
});
我希望在刷新页面时看到警报,这样我就可以开始实际编程了。我试过很多其他的方法,但到目前为止都没有效果。脚本已在小猴子菜单中启用

编辑:脚本部分现在如下所示:

foo();

function foo() {
    $ = unsafeWindow.jQuery;
    $('tr td.row2:nth-child(4)').css("background-color", "#999");
}
它不起作用。我知道jQuery很好,因为我可以在greasemonkey之外运行它。
如果不是jQuery函数,而是说alert('hello');这很好;我在页面加载时收到警报。

首先,我不会将jQuery粘贴到其中。只需使用
@require
Greasemonkey指令(必须在脚本头中)

另外,jQuery赋值是向后的。它应该更像:

function foo() {
  $ = unsafeWindow.jQuery;
  // or jq = unsafeWindow.jQuery, or whatever you'd like to call it

  ...
}

这就是我通常在中所做的。

使用
@require导入的jQuery似乎驻留在窗口中而不是unsafeWindow中。

使用@require是正确的方法(确保您拥有相对最新版本的greasemonkey,因为此功能并不总是存在)。另外值得注意的是,在安装greasemonkey脚本时,@require字符串必须存在,安装后编辑greasemonkey脚本以添加@require将不起作用。因此,如果您的脚本已经安装,请卸载它并在重新安装之前添加@require部分。您可以正常编辑脚本的其余部分,而无需重新安装。从您的一个脚本反向工作使我能够启动并运行。使用@require然后将wget jquery放入脚本目录。您可以将greasemonkey加载代码放入html文件,保存到桌面或Web服务器,然后从那里安装。我正在使用jquery 1.8.1和tampermonkey(chrome),我需要使用unsafeWindow。
function foo() {
  $ = unsafeWindow.jQuery;
  // or jq = unsafeWindow.jQuery, or whatever you'd like to call it

  ...
}