我正在开发一个需要创建可扩展表单的项目,因此用户可以通过单击“添加新项目”按钮来输入任意数量的项目,该按钮将克隆一行并允许他们选择要添加到形成 .
到目前为止,我们有一行元素如下所示:
<div class="input-group">
<select class="form-control name-select" name="name">
<option value disabled selected>Component Name</option>
</select>
<select class="form-control type-select" name="sale_type">
<option value disabled selected>Sale Type</option>
<option value="1">type 1</option>
<option value="2">type 2</option>
</select>
<input type="input" class="form-control" placeholder="number">
<input type="text" class="form-control" placeholder="Total number" readonly>
<input type="text" class="form-control" placeholder="Cost per item" readonly>
<input type="text" class="form-control" placeholder="Total cost" readonly>
</div>
我们目前只是在前端工作,但这些选择将有很多选项 .
我的问题是我们需要能够复制这一行,仍然可以使用select2框 . 从查看它我们意识到我们需要销毁select2,克隆它,然后重新初始化它 . 这不是问题,但出于某种原因,当我们复制项目行时,除了最近创建的那些之外的所有select2框都只是正常选择 . 这就好像它只允许每个select2中的一个不理想,因为我们需要它们的所有工作,以便从多个选项列表中轻松选择 .
我们用来复制项目的代码是:
var base = element.find('.item-row.base').first();
base.find('.name-select').select2('destroy');
base.find('.type-select').select2('destroy');
var itemRowClone = base.clone();
itemRowClone.removeClass('base')
itemRowClone.find('select').each(function(){
$(this).attr('name', $(this).attr('name') + element.find('.item-row').length)
});
element.find('.new-items').append(itemRowClone);
base.find('.name-select').select2();
base.find('.type-select').select2();
itemRowClone.find('.name-select').select2();
itemRowClone.find('.type-select').select2();
console.log('reinitialised')
就像我说的那样,它正在摧毁select2s,但是当它重新初始化时,它只允许每个select的一个实例为select2,其余的都是默认选择 .
如果有人有任何想法,那将是惊人的!
提前致谢
1 回答
最后,我通过复制select2标签来实现它,而不是破坏它 . 然后手动删除由select2生成的span标记,该标记直接位于select标记之后 . 然后我删除了类
select2-hidden-accessible
和属性data-select2-id
,然后在select标签上调用select2()
方法 .希望在这种情况下这有助于其他人!