jQuery clone() doesn't copy <select> DOM

2019-01-20 00:12发布

问题:

Consider the following HTML :

<a id="add" herf="#">add</a>

<div class="list">
    <select>
        <option>1</option>
        <option>2</option>
    </select>
</div>

And Javascript :

$('#add').click(function() {
    var copy = $('.list').last().clone();
    copy.appendTo('body');
});

(OR : http://jsfiddle.net/5A5pN/)

If you choose a select option before clicking Add, you'll notice the newly added select box still uses 1 as its original value, not 2.

Any ways to overcome this?

Thanks!

回答1:

YES! but you can do a workaround. like this,

$('#add').click(function() {
    var orig = $('select',$('.list').last());
    var copy = $('.list').last().clone();
    $('select',copy).val(orig.val());
    copy.appendTo('body');
});

demo