Bootstrap-Select 不响应动态添加 rows/content

Bootstrap-Select doesn't respond to dynamically added rows/content

我有一个 table 行,上面有多个 select 框用于表单输入。

然后我可以克隆该行以创建一个新行。像这样。

var counter = 1;
$(document).ready(function() {
    $('#addItemRow').click(function() {
          $('#itemMultiInputTable tr:last').clone(true,true).insertAfter('#itemMultiInputTable tr:last');

        $('[id^=item_number]:last').attr('id', 'item_number' + counter);
        $('[name^=item_number]:last').attr('name', 'item_number' + counter);

        $('[id^=select_product]:last').attr('id', 'select_product' + counter);
        $('[name^=select_product]:last').attr('name', 'select_product' + counter);

        $('.selectpicker').selectpicker('refresh');
        counter += 1;                   
        return false;                   
    });                                 
});    

但是在动态创建的行上,任何 'select' 框都有 select 选择器框下拉。但是,当我更改第 2+ select 框中的值时,它只会更改第一行的值。

它的第 2 行或第 3 行或其他任何内容都没有关系。当我更改 selectpicker select 框时。只有第 1 行得到更新。并且第 2+ 行始终保持默认值。

好像他们都绑定到第一行,而不是新的(动态添加的)行。

我做错了什么?

谢谢!

找到了答案,至少对我有用。看来我有两个问题。

1) 根据 'issues' 页面 bootstrap-select 找到 here 我了解到 bootstrap select 添加了一个 div class 替换您的 select 框。您必须先删除 class 才能执行任何操作。然后你必须 refresh/reinitialize bootstrap select 在你添加的新行上。

2) 最初在做了所有这些之后,我仍然无法让它工作。原来这是我的克隆(真的,真的)。我假设您想将事件处理程序带到新行。我猜不会。似乎当您克隆事件处理程序时,它将所有内容都绑定回第一行。所以将其更改为 clone() 解决了我的问题。

对于可能 运行 遇到类似问题的任何人,这是我现在可以运行的代码(至少在 firefox 中是这样)。

var counter = 1;
$(document).ready(function() {
   $('#addItemRow').click(function() {

      // Fix this clone() part - must NOT be clone(true,true)
      $('#itemMultiInputTable tr:last').clone().insertAfter('#itemMultiInputTable tr:last');

    $('[id^="item_number"]:last').attr('id', 'item_number' + counter);
    $('[name^="item_number"]:last').attr('name', 'item_number' + counter);

    $('[id^="select_product"]:last').attr('id', 'select_product' + counter);
    $('[name^="select_product"]:last').attr('name', 'select_product' + counter);

    // These are the two key lines to making it work
    $('#itemMultiInputTable tr:last').find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    $('.selectpicker').selectpicker('refresh');
    counter += 1;                   
    return false;                   
 });                                 
});    

我还要注意,这适用于我表单中的所有 3 个 select 字段。我不必在 dividually 中逐一解决,因为它只是替换了 'select' 字段。克隆功能为每个字段提供正确的数据。

我一直在自学这一切,所以如果有人注意到我可以做得更好,我总是渴望学习。

谢谢。