我正在创建表单,我希望用户通过上传按钮上传其多个图像。我的问题是, 假设用户第一次选择2个图像,现在他想再添加3个图像 当它再次上传3张图像时,它显示图像数3.我希望图像计数应为5(第一次上传和第二次上传时的总图像数)。 它将如何运作。
我的代码是:
<input type="file" id="files" name="dog_img[]" class="upload-img" onchange="readURL(this);" multiple>
<input type="hidden" name="img-count" id="img-count" value="0">
jQUERY:
$('#files').change(function () {
var co = 0;
var len = 5;
var preimgcount = $("#img-count").val();
if (preimgcount != 0) {
console.log('preimgcount - ' + preimgcount);
co = parseInt(preimgcount);
len = parseInt(len) - preimgcount;
}
for (var i = 0; i < len; i++) {
var num_of_images = $("#files")[0].files.length;
$("#img-count").attr('value' , num_of_images);
(function (j, self) {
var reader = new FileReader();
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (height < 700 || width < 1000) {
alert("Height and Width must not exceed 1024px.");
return false;
}
};
co++;
console.log('co - ' + co);
$('.gallery-row').append('<div class="col-md-2" id="pip"><span id="' + [co] + '" data-id="' + [co] + '" class="click-form"><img class="imageThumb" src="' + e.target.result + '"/>' + '</span><span data-id="' + [co] + '" class="remove">X</span></div>');
}
reader.readAsDataURL(self.files[j])
})(i, this);
}
});
答案 0 :(得分:1)
修改强>
您的代码中有一些小错误,但它运行正常,co
变量具有正确的值。
以下是工作示例
$('#files').change(function() {
var co = 0;
var len = 5;
var img_count = $("#img-count");
var preimgcount = img_count.val();
if (preimgcount != 0) {
console.log('preimgcount - ' + preimgcount);
co = parseInt(preimgcount);
len = parseInt(len) - preimgcount;
}
for (var i = 0; i < len; i++) {
var num_of_images = $("#files")[0].files.length;
(function(j, self) {
var reader = new FileReader();
reader.onload = function(e) {
var image = new Image();
image.src = e.target.result;
image.onload = function() {
var height = this.height;
var width = this.width;
if (height < 700 || width < 1000) {
alert("Height and Width must not exceed 1024px.");
return false;
}
};
co++;
img_count.val(co);
console.log('co - ' + co);
$('.gallery-row').append('<div class="col-md-2" id="pip"><span id="' + [co] + '" data-id="' + [co] + '" class="click-form"><img class="imageThumb" src="' + e.target.result + '"/>' + '</span><span data-id="' + [co] + '" class="remove">X</span></div>');
}
reader.readAsDataURL(self.files[j])
})(i, this);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="files" name="dog_img[]" class="upload-img" onchange="readURL(this);" multiple>
<input type="hidden" name="img-count" id="img-count" value="0">
&#13;