Javascript 使用jquery创建并复制选择框

Javascript 使用jquery创建并复制选择框,javascript,jquery,select,clone,Javascript,Jquery,Select,Clone,我们希望创建一个新的选择框,并在事件发生时从另一个选择框复制其选项。我们使用以下代码: //Create a new select box and add it to a div $('#content').append("<select id='destination'/>"); //Create copy source options var $options = $("#source > option").clone(); //Append source option t

我们希望创建一个新的选择框,并在事件发生时从另一个选择框复制其选项。我们使用以下代码:

//Create a new select box and add it to a div
$('#content').append("<select id='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$("#destination").append($options);

我有一个有很多选择的页面,有很多选项,上面的代码很慢!有什么方法可以让上面的JS更快吗

您应该设置一个类而不是ID,然后将其附加到上次创建的select中,例如:

$(document).ready(function () {
    $("#btn").click(function () {
        //Create a new select box
        $('#content').append("<select class='destination'/>");
        //Create copy source options
        var $options = $("#source > option").clone();
        //Append source option to destination
        $(".destination").last().append($options);
    });
});

Fiddle:

我宁愿复制源代码并设置一个动态id,因为您可能希望有多个选择框和不同的id,如下所示:

演示@

我将克隆源并更改其ID,而不是克隆每个选项。您应该将ID更改为动态ID或将其全部删除以防止重复示例:
$(document).ready(function () {
    var id = 1;
    $("#btn").click(function () {
        //Create a new select box
        $('#content').append($("#source").clone(true).attr({id: "destination" + id}));
        id++;
    });
});