简体   繁体   English

使用委托来动态添加jQuery Upload File Plugin?

[英]Using delegates for dynamically added jQuery Upload File Plugin?

I am using Jquery Upload File Plugin . 我正在使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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