0

Trying to create an input field for file uploads .. I want when the user selects a file , the file input field gets duplicated with a new empty one

what I used was something like this

<form>
<input type='file' class='addImage' />
</form>


$(function(){ 
        $('.addImage').change(function(){
            $("<input type='file' class='addImage' />").appendTo('form');
        });
    });

See it live here http://jsfiddle.net/R5QSy/1/

It works and display only another single file input duplicate .. if I select a file from the new generated input, no more duplication occurs ! how can I make the duplication process unlimited ? thanks

4

1 回答 1

2

在您的函数附加处理程序时,添加的第二个文件输入尚不存在change,因此它不会响应change事件。您可以改用委托事件处理程序来解决此问题:

$(document).on("change", ".addImage", function(){ ... });

请注意,这可能不会令人满意,因为每次更改任何元素上的选定文件时,都会添加一个新的文件输入(即使表单中已经存在未使用的输入控件)。您可以通过在调用处理程序时向任何元素添加类并在添加新元素之前检查它是否还没有该类来防止这种情况发生。

于 2013-11-08T22:21:32.820 回答