我正在尝试获取多个图像预览器,其中限制为5个选项,如果我想更改我的一个选择,我单击该图像上的x并重新选择一个新图像
我的代码现在显示警告但仍允许随后进行选择。请帮忙!
<input type="file" id="files" name="image_file_arr[]" multiple>
<br><output id="list"></output>
脚本:
$(function() {
$("input#files[type='file']").change(function(){
var $fileUpload = $("input#files[type='file']");
if (parseInt($fileUpload.get(0).files.length)>6){
alert("You can only upload a maximum of 5 files");
return false;
}
});
});
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) { continue; }
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
答案 0 :(得分:1)
请参阅此工作小提琴http://jsfiddle.net/3D6pd/1/
刚刚放
var $fileUpload = $("input#files[type='file']");
if (parseInt($fileUpload.get(0).files.length)>6){
alert("You can only upload a maximum of 5 files");
return false;
}
这个代码在handleFileSelect函数中并使用evt.stopPropagation();
答案 1 :(得分:1)
这是更新的小提琴试试http://jsfiddle.net/3D6pd/6/
我在这里添加了一个表单和一个提交按钮,
$("#sub").click(function(e){
e.preventDefault();
alert("files uploaded="+ $("input#files[type='file']").get(0).files.length);
});
var count=0;
希望这会有所帮助
答案 2 :(得分:1)
我已将此添加到您的小提琴中
$(function() {
var array=[];
$("#sub").click(function(e){
e.preventDefault();
$("input#files[type='file']").get(0).files=array;
alert("files uploaded="+ $("input#files[type='file']").get(0).files.length);
});
var count=0;
// Preview should only have up to 5 images
// onclick x, preview of that image should be deselected and removed from the preview screen
function handleFileSelect(evt) {
var $fileUpload = $("input#files[type='file']");
count=count+parseInt($fileUpload.get(0).files.length);
if (parseInt($fileUpload.get(0).files.length)>6 || count>5){
alert("You can only upload a maximum of 5 files");
count=count-parseInt($fileUpload.get(0).files.length);
evt.preventDefault();
evt.stopPropagation();
return false;
}
var files = evt.target.files;
array = array.concat(files);
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) { continue; }
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview">x</span>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
});