今天下午帮同事改了这样一个bug:
在一个页面中对多张图进行上传时,由于input的value无法情况的问题,导致每次选完图片后,都跟第一张图片一样,无法出现如下效果:
百度了下思路:先将input取到,然后放到一个临时form里面清空,最后删掉form.
代码如下:
首先是生成图片选择和显示部分的绑定代码:
var img_tmp = '<tr><td><input type="text" name="code" value="" style="width: 90%; display: none;"><input type="text" name="title[]" style="width:90%;" /></td><td><input type="text" name="sort[]" style="width:90%;" /></td><td><input type="text" name="num[]" style="width:90%;"/></td>' +
'<td><img alt="" src="" id="" name="img[]" style="max-width: 100px; max-height: 100px; display: block; float: left; border: 1px solid #E6E7EB;" /><div class="file_box">' +
'<input type="button" class="btn" value="选择图片" />'+
'<input type="file" name="fileLOGO" class="file" id="" style="width: 80%;" οnchange="UploadImages(this)" />' +
'</div></td>' +
'<td><a class="del" href="javascript:void(0)">删除</a></td></tr>';
在οnchange="UploadImages(this)" 这里的方法中,我们传入本次点击的input,进行提交:
//多图片上传
function UploadImages(FileInput) {
//var isno = fileChange($(FileInput));
//if (isno == undefined) {
var options = {
type: "POST",
url: '../Handler/AshxUploadFile.ashx?type=Images',
success: function (msg) {
if (msg == "error") {
clearImages($(FileInput));
showerrortip("上传失败");
} else {
if (msg != "errortype") {
clearImages($(FileInput));
$(FileInput).parent().prev("img").attr("src", strPic + msg);
clearImages($(FileInput));
$(FileInput).attr("style", "");
}
}
}, error: function (msg) {
clearImages($(FileInput));
$(FileInput).attr("style", "");
showerrortip("参数异常!");
}
};
// 将options传给ajaxForm
$('form').ajaxSubmit(options);
//}
}
当时因为忽略了对input的清理,才导致了那个问题,为此,加入clearImages函数:
function clearImages(selector) {
var fi;
var sourceParent;
if (selector) {
fi = $(selector);
sourceParent = fi.parent();
}
else {
return;
}
$("<form id='tempForm'></form>").appendTo(document.body);
var tempForm = $("#tempForm");
tempForm.append(fi);
tempForm.get(0).reset();
sourceParent.append(fi);
tempForm.remove();
}
这样,就利用临时form清空了input.