我试图在表单发布之前允许上传多个文件。我希望用户只能看到一个文件上传元素,并且每次选择一个文件时,都会显示一个新的 <li>
包含文件名和图像/链接,用于从集合中删除该特定文件。有一个 jQuery MultiFile 插件可以实现我想要的功能,但我无法让自定义样式按照我想要的方式工作,所以我正在滚动自己的插件。
到目前为止,我有以下代码。它成功添加了 <li>
,隐藏新选择的文件的文件上传元素,并在页面中附加一个空的文件上传元素,供用户选择新文件。我正在努力适本地管理元素的删除,虽然这并不那么困难,但我已经盯着这个问题看了足够长的时间,现在感觉我做的一切都是错的。我希望其他人可能有一些见解,清理这个问题的技巧(即使它更优雅),等等。代码如下。
HTML:
<div id="product-image-area" class="group" style="border-bottom: none; padding-top: 0">
<ul id="photos" class="nobull">
<li id="no-product-images-msg" class="" >
<%= Html.Image("no-photos.png") %>
</li>
</ul>
</div>
<div id="upload-area">
<h4 class="st">Upload an image</h4>
<p class="note">Allowed file types are .gif, .jpg, .jpeg, and .png</p>
<p id="file-input" class="st sb"><input class="photo-upload" id="VenuePhotos_0" name="VenuePhotos[]" type="file" /></p>
</div>
脚本:
$(function () {
$('.photo-upload').live('change', function () {
var fileCount = new Number($(this).parent().children('.photo-upload').length);
$('#photos').append('<li id="venue_photo_' + (fileCount - 1) + '">' + $(this).val() + '<img title="' + (fileCount - 1) + '" src="/vh/public/images/icon-delete.png" class="delete" /></li>');
$(this).parent().append(
$(this).clone().attr('id', 'VenuePhotos_' + fileCount)
);
$(this).hide();
});
$('.delete').live('click', function (e) {
var index = $(e).attr('title');
$('#file-input').children('.photo-upload').remove('#VenuePhotos_' + index);
$('#photos').children().remove('#venue_photo_' + index);
});
});
最佳答案
答案是闭包,这是 JavaScript 最强大的功能之一。其他函数内部的函数 are able to access the variables of the enclosing functions .
您可以在添加文件输入时绑定(bind)删除函数,而不是使用 .live
和动态生成的 ID:
$('.photo-upload').live('change', function () {
var li = $('<li />').text($(this).val()),
img = $('<img src="/vh/public/images/icon-delete.png" class="delete" />'),
input = $(this).clone();
li.append(img);
$('#photos').append(li);
$(this).parent().append(input);
$(this).hide();
img.click(function() {
input.remove();
li.remove();
});
});
在此示例中,删除按钮的 click
处理程序访问在父函数中获取的 jQuery 包装器(对于必须删除的两个元素)。
关于jquery - 使用 jQuery 上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4233791/