0

我正在使用Jquery 上传文件插件。除了我不确定如何使它适用于动态添加的文件上传控件之外,它似乎很完美。文档似乎没有任何这样的例子。

小提琴

<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"
    //  });

});
4

1 回答 1

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");
});
<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>

于 2015-07-09T10:01:56.223 回答