Select2克隆只能工作两次

时间:2015-03-25 09:56:35

标签: clone jquery-select2

我试图克隆一个select2列表和两个文本区域,但它只适用于第一个克隆,我不明白为什么......一个新的眼睛肯定会有所帮助! (克隆没问题,但是select2不适用于第3个克隆)

HTML部分

    <fieldset>
<div id="test">
<div>
<label>Tool Name : </label>
<select class="toollist" name="FSR_tool_id[]" style="width: 350px" />
<option></option>
<option value="1" >bla 1</option>

</select>
<input type="Button" value="ADD ANOTHER TOOL" class="AddTool">
<label>Service Scope</label>
<textarea rows="5" style="width:99%" name="FSR_servicescope[]" class="validate[required]"  />
</textarea>
</br>
<label>Service Description</label>
<textarea rows="10" style="width:99%" name="FSR_servicedesc[]" class="validate[required]" />
</textarea><hr>
</div>
</div>
<input type="hidden" value="0" id="countertool">
</fieldset>

JS部分(我之前调用jquery并选择2)

$('#test .toollist').select2({ //apply select2 to my element
        placeholder: "Search your Tool",
        allowClear: true
        });

$("input[type='button'].AddTool").live('click',
function() {
    var index = $(this).closest('div').index();
    if (index > 0) {
        $(this).closest('div').remove();
    } else {

        $('#test .toollist').select2('destroy');
        //we have to destroy the select2 before cloning
        var $div = $(this).closest('div').clone(true);
        $div.find('input.AddTool').val("DELETE THIS TOOL");
        //to replace the button "add" by another "delete"
        var $input = $div.find('input.exp');
        var index = $('input#countertool').val();
        var id = 'exp' + index;
        index++;
        $('input#countertool').val(index);
        $input.attr('id', id).data('index', index);
        $(this).closest('#test').append($div);
        //then, we re-apply select2 to the lists            
       $('#test .toollist').select2({
        placeholder: "Search your tool !",
        allowClear: true
        });
        };
});

知道我的错误吗?

提前多多感谢!

1 个答案:

答案 0 :(得分:0)

看到这个小提琴:http://jsfiddle.net/omugbdm1/3/这是一个混搭的代码,但是应该这样做。

<div id="test">
    <div id="tooltest0" class="tooltest0">
        <label>Tool Name :</label>
        <select class="toollist" name="FSR_tool_id[]" id="FSR_tool_id0" style="width: 350px" />
            <option></option>
            <option value="1">bla 1</option>
        </select>
    </div>
    <div id="tool-placeholder"></div>
    <div>
        <input type="button" value="Add another" />
    </div>
</div>

$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});


$('input[type=button]').click(function () {

    $('.toollist').select2("destroy");
    var noOfDivs = $('.tooltest0').length;
    var clonedDiv = $('.tooltest0').first().clone(true);
    clonedDiv.insertBefore("#tool-placeholder");
    clonedDiv.attr('id', 'tooltest' + noOfDivs);


    $('.toollist').select2({ //apply select2 to my element
    placeholder: "Search your Tool",
    allowClear: true
    });

});
相关问题