简体   繁体   中英

Create a new element and append a clone to this element

Initial situation looks like this:

<div id="bigDiv">
    <div><input type="file"/></div>
</div>

Desired result after cloning:

<div id="bigDiv">
    <div><input type="file"/></div>
    <div><input type="file"/></div>
</div>

I've tried following statement:

var elm = $('#bigDiv :input[type=file]').change(function(event) {
    console.log('changed');
    $('#bigDiv :input[type=file]').eq(0).clone(true).val('').appendTo('#bigDiv');
});

This works. My Question is, how can I append this new file input element into a new div element, which has to be created before too? (See desired result above)

I think my jQuery statement is improvable too.

It would be easier to clone the entire div . Try this:

var elm = $('#bigDiv :input[type=file]').change(function(event) {
    var $newDiv = $('#bigDiv div').first().clone(true).appendTo('#bigDiv');
    $('input[type="file"]', $newDiv).val('');
});

Example fiddle

One liner: http://jsfiddle.net/6QL3k/2/ , works on created too

var elm = $('#bigDiv').on('change',' :input[type=file]',function(event) {
    console.log('changed');
     $(this).clone().appendTo($(this).parent().parent()).wrap('<div></div>');    
});

http://jsfiddle.net/6QL3k/

  var elm = $('#bigDiv :input[type=file]').change(function(event) {
      console.log('changed');
      var next = $(this).clone();
      var wrapNext = $('<div></div>');
      wrapNext.append(next);
      $(this).parent().after(wrapNext);
  });

Very simple way without using clone

var div = $("#bigDiv").find("div").first().html();
$("input").first().after(div);

WORKING DEMO

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