JQuery 克隆 <select> 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3906644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery clone <select> element
提问by diggersworld
I want to clone a <select> input in HTML using JQuery.
I'm not sure how to go about it, so thought I'd ask here.
我想使用 JQuery 在 HTML 中克隆一个 <select> 输入。
我不知道如何去做,所以想我会在这里问。
Particularly interested in the best way to write it back into the document as well.
特别感兴趣的是将它写回文档的最佳方式也是如此。
My select element looks like this:
我的选择元素如下所示:
<select id="options">
<option value="1">Opt 1</option>
<option value="2">Opt 2</option>
<option value="3">Opt 3</option>
</select>
Thanks.
谢谢。
回答by Plaudit Design
See: http://api.jquery.com/clone/
见:http: //api.jquery.com/clone/
$('select#options').clone().attr('id', 'newOptions').appendTo('.blah');
appendTo(...) is only one way to insert the cloned elements. Other methods can be found here: http://api.jquery.com/category/manipulation/
appendTo(...) 只是插入克隆元素的一种方法。其他方法可以在这里找到:http: //api.jquery.com/category/manipulation/
回答by user754952
How about this?
这个怎么样?
<select id="options">
<option value="1">Opt 1</option>
<option value="2">Opt 2</option>
<option value="3">Opt 3</option>
</select>
//target
//目标
<select id="options2">
</select>
$('#options').find('option').clone().appendTo('#options2');
Thanks.
谢谢。
回答by jesal
Only problem with the accepted answer is that if your select contains optgroups they will not be copied over. In that case, the easiest way I found was to just do this:
接受的答案的唯一问题是,如果您的选择包含 optgroups,它们将不会被复制。在那种情况下,我找到的最简单的方法就是这样做:
$('#options2').html($('#options').html());
回答by user9054011
you can attr option selected true with select change, then use clone is ok.
您可以通过选择更改 attr 选项选择 true,然后使用克隆就可以了。
$("#options").off("change").on("change", function() {
var val = $(this).val();
$(this).find("option[value=" + val + "]").attr("selected", true);
});
$("#options").off("change").on("change", function() {
var val = $(this).val();
$(this).find("option[value=" + val + "]").attr("selected", true);
});