我之前遇到过这种情况,但我对范围有一个公平的理解,但还不够。我正在尝试将一个字符串作为参数传递给一个匿名函数,在for循环中。根据我的理解默认情况下这是递归的,所以无论变量的字符串改变了多少次,它仍会发送相同的字符串(1,2,3,4被传递(可能像?)1,1,1,1当我们想要1,2,3,4)。
我想让这个非递归,所以在下面的例子中,multiple-file-input-element的文件名是不同的(因为它们都不一样)。
我们如何让事件监听器接收非递归参数?
function images_upload(e)
{
for (var i = 0; i < document.getElementById('post_files').files.length; i++)
{
var file = document.getElementById('post_files').files[i];
var n = images_name(file.name);
var xhr = new XMLHttpRequest();
if (typeof xhr.upload=='object')
{
var upload = xhr.upload;
upload.addEventListener('progress', function(e,n)
{
alert('n = '+n);
}, false);
xhr.open('POST','upload.php');
xhr.setRequestHeader('Cache-Control','no-cache');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.setRequestHeader('X-File-Name',file.name);
xhr.send(file);
}
else {var ns = true;}
}
if (ns) {alert('Error: your browser does not support AJAX file uploads.');}
}
是的,我知道我正在测试的内容(在Firefox 10,Chrome 17(?)和Opera 12中测试)。
答案 0 :(得分:1)
考虑以下两个片段:
var i;
for (i = 0; i < 5; i += 1) {
setTimeout(function () {
// here, i will be the loop variable, and thus you'll get
// an ouput of 5, 5 times, because by the time this function will be
// called, the loop will be long finished
console.log(i);
}, 250);
}
for (i = 0; i < 5; i += 1) {
setTimeout(function (i) {
return function () {
// here, i will be the function parameter of the outer function
// which has been called immediately passing in a 'copy' of
// the loop variable.
// output will be: 0, 1, 2, 3, 4
console.log(i);
};
}(i), 250);
}
此外,这与递归无关。
关于您的代码,您应该更改:
upload.addEventListener('progress', function(e,n)
{
alert('n = '+n);
}, false);
为:
upload.addEventListener('progress', function (n) {
return function(e) {
alert('n = ' + n);
};
}(n), false);
答案 1 :(得分:0)
Javascript没有块范围...
试试这个:
function images_upload(e) {
var ns = false;
for (var i = 0; i < document.getElementById('post_files').files.length; i++) {
(function(i) {
var file = document.getElementById('post_files').files[i];
var n = images_name(file.name);
var xhr = new XMLHttpRequest();
if (typeof xhr.upload == 'object') {
var upload = xhr.upload;
upload.addEventListener('progress', function(e, n) {
alert('n = ' + n);
}, false);
xhr.open('POST', 'upload.php');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('X-File-Name', file.name);
xhr.send(file);
}
else {
ns = true;
}
})(i);
}
if (ns) {
alert('Error: your browser does not support AJAX file uploads.');
}
}