我正在尝试允许在表单发布之前多个文件上传。我希望用户只看到一个文件上传元素,并且每次选择一个文件时,都会显示一个新的<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);
});
});发布于 2010-11-21 07:04:41
答案是闭包,它是JavaScript最强大的特性之一。其他are able to access the variables of the enclosing functions中的函数。
您可以在添加文件输入时绑定删除函数,而不是使用.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();
});
});在本例中,delete按钮的click处理程序访问在父函数中获得的jQuery包装器(对于必须删除的两个元素)。
https://stackoverflow.com/questions/4233791
复制相似问题