我正在尝试为每个动态上传的图像动态生成一个id字段。我不知道如何实现它。下面给出的是jquery代码。对此问题的任何想法都将不胜感激。
码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
Find the bellow HTML code
<h2>preview multiple images before upload using jQuery</h2>
<input type="file" id="files" name="files[]" multiple />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
</body>
</html>
答案 0 :(得分:1)
您可以通过保留一些静态id组件动态创建id,并在每次创建新图像时为其添加动态组件。
一个粗略的例子可能是:
<script type="text/javascript">
$(document).ready(function () {
var idStatic = 'Image_'; //Static component of ID
var imgCount = 0; // Dynamic component of ID, will be incremented and appended to idStatic for each new image.
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
imgCount++; // Increment dynamic part, so that id is unique.
$("<img></img>", {
"class": "imageThumb",
src: e.target.result,
id: (idStatic + imgCount), // tell jquery to add the id for new element.
name: 'images[]', // give a name, so that server recognises it on form submit. Can be same as id.
title: file.name,
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
也就是说,除非您希望在添加后对客户端上的图像进行修改,否则您可能不需要id。另外一个名称属性就足够了。