循环GM_xmlhttpRequest在变量上提供“ TypeError Null”
作者:互联网
我在页面中有一些链接.我想计算每个链接的响应,并在链接前面插入数字.这是我所拥有的:
var links = document.evaluate('..../td[1]/font//a[@href]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var headings = document.evaluate('.../td[1]',document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
for(var i = 0; i < links.snapshotLength; i++){
var urls = links.snapshotItem(i).href;
GM_xmlhttpRequest({
method: 'GET',
url: urls,
onl oad function (res){
var dt = document.implementation.createDocumentType("html",
"-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd");
doc = document.implementation.createDocument('', '', dt);
html = doc.createElement('html');
html.innerHTML = res.responseText;
doc.appendChild(html);
var responses = doc.evaluate('.../tr', doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var nResponse = responses.snapshotLength - 1;
var numResponse = document.createElement('font');
numResponse.innerHTML =
'<b>' + nResponse +
'</b>' ;
headings.snapshotItem(i).parentNode.insertBefore(numResponse, headings.snapshotItem(i));
}
});
}
我得到了错误信息:
TypeError: headings.snapshotItem(…) is null
解决方法:
至少有3个问题:
>尝试不关闭而将值传递给GM_xmlhttpRequest的onload.
>循环链接,但尝试索引标题.
> onl oad属性后缺少冒号.
(1)GM_xmlhttpRequest异步操作.这意味着在onload触发时,变量i和标题将是未定义的,或者将是它们的最终值,而不是所需的循环值.
要将值传递给onload,请使用a closure.(在下面的代码中,parseURL提供了闭包.)
(2)变量i在链接上循环,但是代码试图使用它索引标题!两者的数量很少(即使有的话,也很差). “标题”是否始终是链接的父级?如果是这样,请使用它.
放在一起,使用如下代码:
var links = document.evaluate (
'..../td[1]/font//a[@href]', document, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
//-- "Headings" are relative to links
for (var J = links.snapshotLength - 1; J >= 0; --J) {
var targUrl = links.snapshotItem (J).href;
parseURL (targUrl, J);
}
function parseURL (targUrl, J) {
GM_xmlhttpRequest ( {
method: 'GET',
url: targUrl,
onl oad: function (res) {
var dt = document.implementation.createDocumentType (
"html", "-//W3C//DTD HTML 4.01 Transitional//EN",
"http://www.w3.org/TR/html4/loose.dtd"
);
var doc = document.implementation.createDocument ('', '', dt);
var html = doc.createElement ('html');
html.innerHTML = res.responseText;
doc.appendChild (html);
var responses = doc.evaluate (
'.../tr', doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
var nResponse = responses.snapshotLength - 1;
var numResponse = document.createElement ('font');
numResponse.innerHTML = '<b>' + nResponse + '</b>';
var heading = links.snapshotItem (J).parentNode.parentNode;
heading.parentNode.insertBefore (numResponse, heading);
}
} );
}
标签:javascript,greasemonkey,typeerror,gm-xmlhttprequest 来源: https://codeday.me/bug/20191013/1904707.html