为什么在GreaseMonkey中尝试使用jQuery时$未定义? [英] Why is $ undefined when I try to use jQuery in GreaseMonkey?

查看:123
本文介绍了为什么在GreaseMonkey中尝试使用jQuery时$未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对GreaseMonkey完全陌生,但我正在尝试编写一些脚本.

I'm totally new to GreaseMonkey, but I'm trying to make a little script.

// ==UserScript==
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// ==/UserScript==
(function() {
    $ = unsafeWindow.jQuery;
    alert($); // this gives 'undefined'
}());

为什么警报给出undefined以及如何解决此问题?

Why does the alert give undefined and how to fix this?

更新

我尝试过:

(function(){
  //boilerplate greasemonkey to wait until jQuery is defined...
  function GM_wait()
  {
    alert('ok');
    if(typeof unsafeWindow.jQuery == 'undefined')
      window.setTimeout(GM_wait,100);
    else
      unsafeWindow.jQuery(function() { letsJQuery(unsafeWindow.jQuery); });
  }
  GM_wait();

  function letsJQuery($)
  {
    alert($);
  }
})(); 

但是,这给了我无限的警报提示.似乎jQuery根本没有加载.

but this gave me an infinite loop of ok-alerts. Seems like jQuery doesn't get loaded at all.

推荐答案

编辑:是

也许您的Greasemonkey版本不够新.是版本0.8添加了@require.另外,请记住,仅在首次安装脚本时才处理 @require.如果更改了所需脚本的列表,则需要将其卸载并重新安装; Greasemonkey在安装一次后下载所需的脚本,然后使用缓存的副本.

Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require. Also, remember that @require is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall it and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter.


可以在页面准备就绪之前(即jQuery初始化之前)执行GM脚本.为了使用jQuery,我在Greasemonkey脚本中使用了以下代码:


The GM script could be executing before the page is ready (i.e. before jQuery has initialized). I use this code in my Greasemonkey scripts in order to use jQuery:

(function(){
  //boilerplate greasemonkey to wait until jQuery is defined...
  function GM_wait()
  {
    if(typeof unsafeWindow.jQuery == 'undefined')
      window.setTimeout(GM_wait,100);
    else
      unsafeWindow.jQuery(function() { letsJQuery(unsafeWindow.jQuery); });
  }
  GM_wait();

  function letsJQuery($)
  {
    //whatever
  }
})();

这篇关于为什么在GreaseMonkey中尝试使用jQuery时$未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆