我有一个相当简单的任务来替换页面上的特定文本。假设有 10 个 DIV,每个 DIV 包含一个特定信息。我想根据数据库检查此信息,并将文本替换为数据库中的结果。
我将 GM_xmlhttpRequest 放置在一个循环内,该循环应检查此信息并为 10 个 DIV 中的每一个替换它。不幸的是,这不起作用,最后一个 DIV 包含 10 个完全相同的信息。也就是说,当i=10时,GM_xmlhttpRequest被执行10次。
下面是一个简化的代码:
var i=1;
while (i<=10) {
var id = 'div-' + i; //This sets the name of the DIV
var ShowContent = document.getElementById(id);
GoToURL = "http://domain.com/?=" + id; //This specifies a URL that changes on every loop
GM_xmlhttpRequest({
method: "GET",
url: GoToURL,
onload: function(response) {
ShowContent.innerHTML = response; //This should replace the information for each DIV
alert(i); //TEST: this shows always 11 (even not 10!). Why?
}
});
i++;
)
最佳答案
Ajax 是异步的,因此当传递响应时,您的循环将已经结束(因此 i=11
)。
但是您可以使用闭包来处理响应函数中的'i'
:
var i=1;
while (i<=10) {
(function(i){
var id = 'div-' + i; //This sets the name of the DIV
var ShowContent = document.getElementById(id);
GoToURL = "http://domain.com/?=" + id; //This specifies a URL
GM_xmlhttpRequest({
method: "GET",
url: GoToURL,
onload: function(response) {
ShowContent.innerHTML = response; //This should replace the information for each DIV
alert(i);
}
});
})(i);
i++;
}
关于javascript - WHILE 循环内的 GM_xmlhttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161063/