jQuery Bootstrap Select - 在动态添加的元素上重新初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23514318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:17:41  来源:igfitidea点击:

Bootstrap Select - reinitialize on dynamically added element

jquerytwitter-bootstrapselectbootstrap-select

提问by user1049961

I'm using Bootstrap Select (http://silviomoreto.github.io/bootstrap-select/) for displaying dropdown with Font-Awesome icons for each section of my website.

我正在使用 Bootstrap Select ( http://silviomoreto.github.io/bootstrap-select/) 为我的网站的每个部分显示带有 Font-Awesome 图标的下拉列表。

I added ability to add new sections - when clicked on add button, a new section (duplicate of previous section) is added. In this section, the Bootstrap Select doesn't work.

我添加了添加新部分的功能 - 单击添加按钮时,会添加一个新部分(上一部分的副本)。在本节中,Bootstrap Select 不起作用。

I tried to reinitilize it like:

我试图重新初始化它,如:

var select = $('[name="section['+ numbersection +'][section_icon]"]');
$(select).selectpicker('destroy');
$(select).selectpicker({
  showIcon: false
});

That doesn't work though, as the detroy method doesn't seem to fire. Is there a way to reinitilize Bootstrap Select on dynamically added element?

但这不起作用,因为 detroy 方法似乎没有触发。有没有办法在动态添加的元素上重新初始化 Bootstrap Select?

回答by Seb33300

You have to refresh your select as mentioned on the plugin page

您必须按照插件页面上的说明刷新您的选择

$(select).selectpicker('refresh');

回答by Manwal

refresh()

刷新()

To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.

要使用 JavaScript 以编程方式更新选择,首先操作选择,然后使用刷新方法更新 UI 以匹配新状态。在删除或添加选项时,或者通过 JavaScript 禁用/启用选择时,这是必要的。

$(".selectpicker").selectpicker('refresh');

Demo

演示