【问题标题】:How to clone a jQuery Chosen select box with dynamically populated options?如何克隆具有动态填充选项的 jQuery Chosen 选择框?
【发布时间】:2013-06-13 18:26:07
【问题描述】:

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

我可以克隆所选元素,但它生成的 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;
};

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

谢谢, 贾亚克里希纳

【问题讨论】:

  • 是否有理由需要克隆 Chosen 生成的元素?克隆
  • 这应该是一条评论
  • 是的,我试过了。但由于某种原因,我无法在上面应用类(chzn-select)。 code var $newRow = $("#costTemplateRow").clone(true); var rowLen = $(".costTemplateRow").length; $newRow.find('select').each(function (){ var curId = $(this).attr('id'); $(this).attr('id',curId+rowLen); $(this ).attr('class','chzn-select'); }); $newRow.show(); $('#costsTable tr:last').before($newRow); code
  • 谢谢,我尝试克隆一个简单的选择下拉菜单,然后在上面应用“选择”样式。我没有在所选课程上调用更新列表事件,因此之前没有工作。再次感谢您的投入。

标签: jquery select drop-down-menu clone


【解决方案1】:

似乎问题在于克隆仍然与原始对象共享一些数据。来自 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

希望对你有帮助

【解决方案2】:

好吧,这就是我用动态填充选项克隆所选控件的方法。也许是更好的方法,但没有更多关于 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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2016-10-16
    • 2020-04-01
    • 2011-12-26
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    相关资源
    最近更新 更多