动态ID生成使用JavaScript
问题描述:
我想创建与删除选项多图片上传文件阅读器(),到现在我能够选择独特的多个文件,但我想有。对于一个删除选项我不得不产生ID为每个图像在上传之前将其删除:动态ID生成使用JavaScript
window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var dive = $(".overview").find('img').length;
var output = document.getElementById("result");
// console.log(files);
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
$(".overview .imgdivcon").each(function(){
var its =$(this).children().eq(1).attr("title");
if(its == file.name){
throw alert("already exits") ;
}
});
var divn = i+dive+1;
var picReader = new FileReader();
console.log(divn);
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.className="imgdivcon";
div.innerHTML = "<p onclick='sliceimg("+divn+")' class='close' name='"+i+"' id='cl'>x</p><img width='150' height='150' class='thumbnail' src='" + picFile.result + "'" +
"title='" + file.name + "'/>";
output.insertBefore(div,null);
});
//Read the image
picReader.readAsDataURL(file);
}
});
当我选择单个图像生成的唯一的ID为每个图像,但是当我选择多张图像它给总的图像,计数为每个图像而不是一个独特的计数。
这里是我JS提琴链接http://jsfiddle.net/aerfan/CdgUV/一点帮助时便会aprreciated。
答
你有错唯一的ID(应该是图像,而不是总数的顺序)当您选择多张图像,因为“DIVN”变量将是图像的总数被触发picReader负载事件处理程序。
闭幕会创建功能时,局部变量添加到其范围。在执行文件读取器加载回调之前完成的for循环外部和divn将是图像的总数。
for(var i = 0; i< files.length; i++)
{
......
var divn = i+dive+1; //this variable will be added to callback closure
.......
picReader.addEventListener("load",function(event){
........
//divn is always the total count of images
div.innerHTML = "<p onclick='sliceimg("+divn+")' class='close' name='"+i+"' id='cl'>x</p><img width='150' height='150' class='thumbnail' src='" + picFile.result + "'" +
"title='" + file.name + "'/>";
output.insertBefore(div,null);
});
}
要解决此问题,您可以尝试使用柯里技术。让我们更新picReader负载事件回调:
picReader.addEventListener("load",(function(divn){
return function(event){
var picFile = event.target;
var div = document.createElement("div");
div.className="imgdivcon";
div.innerHTML = "<p onclick='sliceimg("+divn+")' class='close' name='"+i+"' id='cl'>x</p><img width='150' height='150' class='thumbnail' src='" + picFile.result + "'" +
"title='" + file.name + "'/>";
output.insertBefore(div,null);
};
})(divn));
您可以预先填入参数(DIVN),使用封闭记住它的状态,并通过使用钻营返回新功能。
希望这对你有所帮助。
感谢它真的帮了我很多。你可以请你提供一个参考链接来学习柯里技术 – Irfan
你可以阅读Resig的文章[JS中的部分应用](http://ejohn.org/blog/partial-functions-in-javascript/)。 – Chickenrice