当我运行此代码时,警报2显示6个不同的href链接。警报3显示最后一次href 6次。我如何使它使用相同的对象(linkdom aka thelink)作为警报2。
注意:这是一个paintmonkey脚本
{
var linkdom = thelink;
alert('2' + linkdom.getAttribute("href"));
GM_xmlhttpRequest({
method: 'GET',
url: href,
onload: function(resp){
//...
alert('3' + linkdom.getAttribute("href"));
}
});
//...
}
答案 0 :(得分:1)
如果这是你自己的功能,我会说把它作为参数传递。或者如果JavaScript有默认参数,我会说将其作为默认参数传递。现在的样子,虽然......尝试这个。
{
var linkdom = thelink;
alert('2' + linkdom.getAttribute("href"));
GM_xmlhttpRequest({
method: 'GET',
url: href,
onload: (function() {
var localvar = linkdom;
return function(resp){
//...
alert('3' + localvar.getAttribute("href"));
}})()
});
//...
}
这将创建一个外部函数,并将局部变量设置为当前值linkdom
。然后它创建您的函数并返回它。然后我立即应用外部函数来恢复你的功能。外部函数不会共享相同的局部变量,因此代码应该可以工作。