看看下面的代码,我正试图提醒reader.onloadend
中i
的值,它没有正确显示,它显示了i
的最大值,即如果i
添加3个图像i
,只提醒三个,它应该显示0,1和3。
$("#files2").change(function()
{
var src=$("#files2").val();
if(src!="")
{
formdata= new FormData();
var numfiles=this.files.length;
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
//alert(i);
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/))
{
if((Math.round(size))<=(1024*1024))
{
var reader = new FileReader();
reader.readAsDataURL(file);
$("#preview").show();
$('#preview').html("");
//<img src="img/remove.png"/>
//style='margin-left: -16px;margin-top: -6px;'
alert(i);
reader.onloadend = function(e)
{
var image = $('<img id="im'+i+'" style="float:left; height: 150px; width: 125px; margin-left: 5px; margin-right: 10px; margin-bottom: 10px;">').attr('src',e.target.result);
var image1 = $('<img onclick="$(this).remove();$("#im1").remove();" style=" margin-left: -25px;margin-top: -1px;z-index: 1;position: absolute; ">').attr('src','img/remove.png');
$(image).appendTo('#preview');
$(image1).appendTo('#preview');
};
formdata.append("files2[]", file);
if(i==(numfiles-1))
{
$(".nextim").click(function(){
$.ajax(
{
url: "upload.php?contactid=<?php echo $id1; ?>&postid=<?php echo $id2; ?>",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res)
{
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
return false;
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
据我所知,您应该循环使用所使用的文件数量。由于您还没有向我们展示如何初始化变量i
,所以我尝试使用该名称作为示例。希望这能帮助你:)
for (var count = 0; count < files.length; count ++) {
(function(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
alert(name );
}
})(files[count]);
}