简体   繁体   中英

Using delegates for dynamically added jQuery Upload File Plugin?

I am using Jquery Upload File Plugin . It seems perfect except that I am not sure how to make it work for dynamically added file upload controls. Documentation doesn't seem to have any such example.

FIDDLE

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

});

What you're doing is the one of the right ways of doing it as the plugin can't be bound to elements that do not exist when the page was first loaded. Here is another way of doing it, which is a bit cleaner (I think) using custom events. I have added inline comments where necessary to explain the code.

 //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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM