bootstrap-4 - 将选项动态添加到 Bootstrap 可搜索选择
问题描述
当我尝试将选项动态添加到 Bootstrap 可搜索选择时,它是在选择之外添加的。请看截图
如何正确地将选项动态添加到 Bootstrap 可搜索选择
这是我的代码
<div class="row form-group">
<select class="col form-control selectpicker supplierSelect" data-live-search="true"
title="Select Supplier..." data-size="5">
<option th:each="supplier : ${suppliers}" th:value="${supplier.id}" th:text="${supplier.name}"></option>
</select>
<button type="button" class="btn mb-1 btn-rounded btn-outline-info"
data-toggle="modal" data-target="#addSupplier"><span><i class="fa fa-plus"></i> </span>
</button>
</div>
这就是我添加数据的方式
document.querySelector(domStrings.saveSupplierButton).addEventListener('click', function () {
const data = JSON.stringify(uiController.getSupplierData());
console.log(data);
const url = window.location.protocol + "//" + window.location.hostname+":"+window.location.port+"/supplier";
const otherParams = {
headers: {"content-type": "application/json; charset=UTF8"},
body: data,
method: "POST"
};
fetch(url, otherParams)
.then(data=>{return data.json()})
.then(data => {
console.log(data);
let template = '<option value="{optVal}">{text}</option>';
template = template.replace('{optVal}',data['id']).replace('{text}',data['name']);
$(domStrings.supplierSelect).append($.parseHTML(template));
$(domStrings.supplierSelect).selectPicker('refresh');
//fixme
})
.catch(error=>console.log(error))
});
但这不起作用。我的代码有什么问题?
解决方案
首先检查传入数据的格式是否正确。总结这一点,我将专注于在接收新数据后用于生成option
标签的技术。目前正在每次获取数据时使用字符串设置一个变量,用新值替换它并使用parseHTML
. 可以使用 ES6 字符串文字和$
方法来减少它:
$select.append($(`<option value="${value}">${text}</option>`));
我对此做了一个简单的示例概念:https ://codepen.io/geekzolanos-dev/pen/bGdgvqq
推荐阅读
- vba - 使用 Access VBA 问题将 PDF 合并为一个 PDF 文件
- jmeter - 如何将不同数量的线程设置为不同的线程组?
- c# - 模拟将方法调用返回到另一个对象的方法
- asp.net - 使用请求流和一些数据时,使用 HttpWebRequest 调用 API 会返回 404 错误,如何解决?
- android - 有没有办法在 Android 和 iOS 上生成一个链接,如果已安装,则在 Firefox 中打开,如果没有,则指向 AppStore/GooglePlay 安装 FF
- c++ - 处理二维动态分配的数组
- ravendb - RavenDB 从 3.5 迁移到 5.0.3 引发重复键错误
- javascript - 用多个键和值填充对象数组
- django - Django Cache 我可以部分清除特定对象视图的缓存吗?
- excel - 排除隐藏在 For Each 函数中的某些工作表