我正在使用Jquery Upload File Plugin。它看起来很完美,除了我不确定如何使其适用于动态添加的文件上传控件。文档似乎没有任何这样的例子。
<div id="container">
<div class="fileuploader">Upload</div>
</div>
<button id="btnadd">CLICK</button>
$(".fileuploader").uploadFile({
url: "YOUR_FILE_UPLOAD_URL",
fileName: "myfile"
});
$('#btnadd').on('click', function () {
$("#container").append('<div class="fileuploader">Upload</div>');
//-----if i uncomment this, it would work. But I want to avoid this.
// $(".fileuploader").uploadFile({
// url:"YOUR_FILE_UPLOAD_URL",
// fileName:"myfile"
// });
});
答案 0 :(得分:0)
您正在做的是正确的方法之一,因为插件无法绑定到首次加载页面时不存在的元素。这是另一种方法,使用自定义事件更清洁(我认为)。我已经在必要时添加了内联注释来解释代码。
//Let's use a custom event - controlAdded
$("#container").on("controlAdded", function() {
//Filter the elements that are not hidden
//as file upload plugin hides the element it's bound
//to which means, the plugin has already been bound to
//that particular element!.
$(".fileuploader:not(:hidden)").uploadFile({
url: "YOUR_FILE_UPLOAD_URL",
fileName: "myfile"
});
//trigger on ready since we need to account for
//the elements that the page is loaded with.
}).trigger("controlAdded");
$('#btnadd').on('click', function () {
$("#container")
.append('<div class="fileuploader">Upload</div>')
//Trigger the custom event as and when a new element is added
.trigger("controlAdded");
});
&#13;
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script>
<div id="container">
<div class="fileuploader">Upload</div>
</div>
<button id="btnadd">CLICK</button>
&#13;