Bootstrap SelectPicker在初始化时复制选择列表

时间:2014-10-04 21:11:54

标签: javascript jquery twitter-bootstrap

通过克隆html使用javascript动态创建选择列表后,在创建选择列表后,使用$(MySelectList).selectPicker();初始化选择列表的尝试似乎已经成功,但在调用.selectPicker()之后它似乎重复几个选择。

如果没有.selectPicker()调用,克隆行中有三个下拉列表,但您无法更改值(列表会打开,但选择不会取值)。

调用.selectPicker()后,新行的下拉列表会显示所选值,但现在总共有5个选择列表。另外两个列表是dup。

这就是它的全部内容:

 <div id="advSearchRows" class="clearfix">

    <!-- Form Row Template -->

    <div class="row clone" id="ASR1">
        <div class="form-group">
            <select class="selectpicker include">
                <option>Must Include</option>
                <option>Must NOT Include</option>
            </select>
        </div>
        <div class="form-group">
            <select class="selectpicker match">
                <option id="-1">foo</option>
                <option id="0">bar</option>
                <option id="1">fubar!</option>
            </select>
        </div>
        <div class="form-group">
            <input type="text" class="search-text form-control" placeholder="Keyword Text">
        </div>
        <div class="form-group remove hidden"></div>
    </div>

</div>

行重复代码

var numRows = $("#advSearchRows .clone").length;        // how many rows currently
    var lastRow = $("#advSearchRows .clone:last");          // the last row in the list
    var lastId = lastRow.attr("id").replace("ASR", "");     // the id of the last item
    if(numRows < 5) { // duplicate (clone) template row:     
        var id = parseInt(lastId) + 1;                      // the numeric id of the new row
        var newRow = lastRow.clone().attr("id", id);        // actual cloned row
        newRow.find("select.include")
            .attr("id", "include" + id)
            .selectpicker(); // include ddl id
        newRow.find("select.match")
            .attr("id", "match" + id)
            .selectpicker();     // match ddl id
        newRow.insertAfter("div.clone:last").slideDown('slow');
        $("#" + id).find(".remove").removeClass("hidden");

我想知道我的选择器是否有问题... newRow.find("select.match").attr("id", "match" + id).selectpicker()但根据文档看起来是正确的......也许我有些遗漏。

1 个答案:

答案 0 :(得分:1)

抱歉,我找到了解决方案。基本上我需要一个未初始化的隐藏模板,克隆模板,然后初始化。容易Peasy。

//
// Handle "Add" row button event:

function cloneRow() {
    var numRows = $("#advSearchRows .clone").length;
    var lastRow = $("#advSearchRows .clone:last");
    var template = $("#advSearchRows #ASR1");
    if (numRows >= 6) return false;
    var id = parseInt(lastRow.attr("id").replace("ASR", "")) + 1;
    var newRow = template.clone().removeClass("hidden").attr("id", id);
    newRow.find("select.include").attr("id", "include" + id).selectpicker();
    newRow.find("select.match").attr("id", "match" + id).selectpicker();
    newRow.insertAfter("div.clone:last").slideDown('slow');                
    $("#" + id).find(".remove").removeClass("hidden");
    return false;
}