我使用$.get()函数来处理很多文件,我需要找出我在回调函数中调用的文件名。有办法做到这一点吗?
while (allFilesToImport.length > 0) {
var fileToOperate = allFilesToImport.shift();
var jqxhr = $.get(path + '/' + fileToOperate,
function(data, textStatus, jqXHR){ // here I need the fileToOperate variable!});
最佳答案
您可以在函数内访问 fileToOperate
和 mypathToTheFile
- 这就是闭包很棒的原因之一。
这是一个带有循环的示例,以防万一您有:
var filenames = ['a', 'b', 'c'];
for(var i = 0; i < filenames.length; i++) {
(function(filename) {
$.get('whatever/'+filename, function(data) {
// here you can use filename and it will point to the correct value
});
})(filenames[i]);
}
您还可以使用$.each()
来迭代数组:
$.each(filenames, function(i, filename) {
$.get('whatever/'+filename, function(data) {
// here you can use filename and it will point to the correct value
});
});
关于javascript - 在 jquery 的 $.get 回调函数中使用文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10382684/