Select2动态元素不响应事件

时间:2013-02-28 13:46:21

标签: javascript jquery jquery-select2

我使用Select2效果很好。但是我使用下面的代码来创建新的动态select2下拉菜单,但是点击它们时它们不会反应/打开。

var relationshipcounter = 0;

$('#AddMoreRelationships').click(function () {
    var $relationship = $('.relationship'); // div containing select2 dropdown
    var $clone = $relationship.eq(0).clone();
    $clone[0].id = 'id_' + ++relationshipcounter;
    $relationship.eq(-1).after($clone);

    $relationship.find('select').trigger('change'); // not working
});

截图:

enter image description here

的jsfiddle:

http://jsfiddle.net/pHSdP/133/

5 个答案:

答案 0 :(得分:3)

我有这个确切的问题,当然,我尝试的第一件事是带有数据的深层复制:

el.clone(true,true);

哪个不起作用。相反,我发现的最佳方法是:

el=other_el.clone()_etc; // cloning the old row
el.find('.select2-container').remove();
el.find('select').select2({width: 268});
这两个片段中的

eldiv行,其中包含select,因此包含Select2元素。

基本上我在第二个片段中执行的操作是删除“old”select2,它将始终具有.select2-container类,然后在我新行中所有找到的select元素上重新创建它。

答案 1 :(得分:2)

您需要使用clone参数调用true来复制事件和数据。否则只会克隆元素,而不是绑定到它的事件。

$relationship.eq(0).clone(true);

文档:http://api.jquery.com/clone/

答案 2 :(得分:2)

好的,问题解决了,小提琴:

http://jsfiddle.net/WrSxV/1/

// add another select2
var counter = 0;
$('#addmore').click(function(){
    var $relationship = $('.relationship');
    var $clone = $("#RelationshipType").clone();
    $clone[0].id = 'id_' + ++counter;
    $clone.show();
    $relationship.eq(-1).after($clone);
    $clone.select2({ "width" : "200px" });// convert normal select to select2

    //$('body').select2().on('change', 'select', function(){
      //  alert(this.id);
    //}).trigger('change');

    return false;
});

答案 3 :(得分:0)

使用.on将动态插入的元素绑定到

等事件
$('body').on('click','#AddMoreRelationships',function () {
});

答案 4 :(得分:0)

克隆对象后,您必须为em重新分配事件:

var $clone = $relationship.eq(0).clone();
$clone.on("click", function_name);