如何使用动态填充的选项克隆jQuery Chosen选择框?

克隆现有选定元素(不是选项而是整个选择框)并为它们创建动态ID时,我遇到了问题。

我能够克隆所选元素,但它具有与所选父元素相同的id,并且不允许在那里选择一个选项。

当我单击新生成的选定框时,选择的已克隆父项将显示要选择的选项列表,而不是选择的子项。 选择的孩子被冻结了,我无法选择其中的选项。

截图:

JS:

$("#addCostDetailsRowBtn").button().click(addCostRowFn); var addCostRowFn = function () { var rowLen = $(".costTemplateRow").length; //alert(rowLen); var $newRow = $("#costTemplateRow1").clone(true); $newRow.find('select').each(function () { //alert($(this)); //alert($(this).attr('id')); var item = $(this).attr('id'); if('undefined'!=item) { var newItem = item.replace(/^(.*)(\d+)$/, function(match, p1, p2) { return p1+(parseInt(p2)+1); }); $(this).attr('id', newItem); $(this).removeClass("chzn-done"); } }); $('#costsTable tr:last').before($newRow); return false; }; 

有人可以帮我解决问题吗?

谢谢,Jaya Krishna

似乎问题是克隆仍然与原始对象共享一些数据。 来自Jquery文档http://api.jquery.com/clone/

通常,绑定到原始元素的任何事件处理程序都不会复制到克隆。 可选的withDataAndEvents参数允许我们更改此行为,并改为将所有事件处理程序的副本绑定到元素的新副本。 从jQuery 1.4开始,所有元素数据(由.data()方法附加)也会复制到新副本。

但是,元素数据中的对象和数组不会被复制,并且将继续在克隆元素和原始元素之间共享。 要深度复制所有数据,请手动复制每个数据:

 var $elem = $('#elem').data( "arr": [ 1 ] ), // Original element with attached data $clone = $elem.clone( true ) .data( "arr", $.extend( [], $elem.data("arr") ) ); // Deep copy to prevent data sharing 

希望这可以帮助

那么,这就是我用克隆动态填充选项克隆选定控件的方法。 也许是一种更好的方法,但没有关于jquery缓存/克隆的更多信息,这至少可行。

 var $parent = $('#myThingParentNode'); var clonePropDdl = $parent.find('.chosenProperty').clone(); //get selected value of chosen venue control var clonePropDdlVal = $venue.find('.chosenProperty').val(); //find the element to add the new Chosen control var $newCloneElem = $('#newPropCloneElement'); //add the new clone $newCloneElem.append(clonePropDdl); //initialize the clone $newCloneElem.chosen({ width: "150px" }); //delete the cloned chosen detritis!! This is what makes this work **$newCloneElem.find('.chosen-container:eq(1)').remove();** //set the selected value of the new clone to value of the clone source $newCloneElem.val(lastVenueVal).trigger('chosen:updated');