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

2019-01-19 23:57发布

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条回答
SAY GOODBYE
2楼-- · 2019-01-20 00:13

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

查看更多
登录 后发表回答