我在一个页面中有一些链接。我想计算每个链接的响应并在链接前面插入数字。这是我所拥有的:
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,
onload 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。 - 在
links
上循环,但试图索引headings
。 onload
属性后缺少冒号。
(1) GM_xmlhttpRequest
异步操作。这意味着当 onload
触发时,变量 i
和 headings
要么是未定义的,要么是它们的最终值,而不是你的循环值想要。
要将值传递给 onload
,请使用 a closure . (在下面的代码中,parseURL
提供了闭包。)
(2) 变量 i
在 links
上循环,但代码试图用它来索引 headings
!每个都有相同数量的可能性很小(即使有,也是不好的做法)。 “标题”总是链接的父级吗?如果是这样,请使用它。
将它们放在一起,使用如下代码:
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,
onload: 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 - 循环 GM_xmlhttpRequest 在变量上给出 "TypeError Null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434961/