我如何从我的GreaseMonkey脚本调用添加到jQuery对象的函数

How can I call a functions added to the jQuery Object from my GreaseMonkey script?

本文关键字:添加 jQuery 对象 函数 调用 脚本 我的 GreaseMonkey      更新时间:2023-09-26

我已经创建了一个基于页面内脚本的GreaseMonkey脚本,我想在一个网站上使用,但是我有以下问题:

在脚本中,我们已经创建了包含大量函数的命名空间(brickJax),并且我需要jQuery,因为我们也使用jQuery replaceText函数。

当我从replaceSet调用replaceText函数时,我在控制台上得到以下错误:

未捕获的异常:TypeError: $(node)。replaceText不是一个函数

然而,调用它作为GM_xmlhttpRequest onload回调的一部分工作良好。

var brickJax = (function ($) {
  "use strict";
  var brickJax = {};
  //[Code here]
  function replaceSet(node, str, number, colour) {
    var text = '<a href="http://www.peeron.com/inv/sets/' + number + '-1">'
               + number + ' on Peeron</a>';
    // THIS LINE THROWS THE ERROR:
    $(node).replaceText(str, text);
  }
  function replaceImage(node, str, number, colour) {
    getBricksForImage(number, colour, node, str);
  }
  function getBricksForImage(number, colour, node, str) {
    GM_xmlhttpRequest({
        method: "POST",
        url: "http://brickjax.doodle.co.uk/bricks.aspx/JsonDetails/" + number 
             + "/" + colour,
        dataType: "jsonp",
        onload: function (data) {
            // THIS CALL WORKS PERFECTLY
            $(node).replaceText(str,
                                buildImage($.parseJSON(data.responseText)));
        }
    });
  };
  function buildImage(ajaxData) {
    var text = '<img style="max-height:100px;" src="' + ajaxData.Src 
               + '" alt="' + ajaxData.AltText + '" />';
    return text;
  }
  function replaceTags(element) {
    var elements = $(element).find('*').andSelf();
    elements = elements.not($('script,noscript,style,textarea,pre,code')
                       .find('*').andSelf());
    searchText(elements, /'[part:(['w'-]*)(?::(['w'-]*))?']/gi, replaceImage);
    searchText(elements, /'[set:(['w'-]*)(?::(['w'-]*))?']/gi, replaceSet);
  };
})(jQuery);
brickJax.replaceTags($('body'));
(function ($) { $.fn.replaceText = function (b, a, c) { [...] } })(jQuery);

在实际的脚本中,我添加了日志记录,这表明node在这两种情况下都是HTML元素。

我在replaceSet的调用中做错了什么,这与导致此错误的回调调用不同?

在宿主版本中,两个调用都按预期工作。

为这一大堆的脚本道歉,我已经尽力把它精简到最基本的部分。

这要么是闭包相关的,要么是由于函数定义在表达式而不是声明

无论哪种方式,解决方案都应该是相同的,将replaceText的定义物理地移动到var brickJax = ...之前。