![](/img/trans.png)
[英]Greasemonkey - Button Added to a <div> I added, not calling my greasemonkey functions
[英]How can I call a functions added to the jQuery Object from my GreaseMonkey script?
我已经基于要在网站上使用的页内脚本创建了GreaseMonkey脚本,但是存在以下问题:
在脚本中,我们创建了包含大部分函数的命名空间( brickJax
),并且在使用jQuery replaceText函数的同时,我还需要jQuery。
当我从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 = ...
东西之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.