Bootstrap 4 向引导搜索选择动态添加选项
当我尝试将选项动态添加到引导搜索选择时,它是在选择之外添加的。请看截图 如何正确地将选项动态添加到Bootstrap searchable select 这是我的密码Bootstrap 4 向引导搜索选择动态添加选项,bootstrap-4,thymeleaf,bootstrap-selectpicker,select-options,Bootstrap 4,Thymeleaf,Bootstrap Selectpicker,Select Options,当我尝试将选项动态添加到引导搜索选择时,它是在选择之外添加的。请看截图 如何正确地将选项动态添加到Bootstrap searchable select 这是我的密码 <div class="row form-group"> <select class="col form-control selectp
<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))
});
document.querySelector(domStrings.saveSupplierButton).addEventListener('click',function(){
const data=JSON.stringify(uiController.getSupplierData());
控制台日志(数据);
常量url=window.location.protocol+“/”+window.location.hostname+“:“+window.location.port+”/supplier”;
常量otherParams={
标题:{“内容类型”:“应用程序/json;字符集=UTF8”},
正文:数据,
方法:“员额”
};
获取(url、其他参数)
.then(数据=>{return data.json()})
.然后(数据=>{
控制台日志(数据);
让模板=“{text}”;
template=template.replace('{optVal}',data['id'])。replace('{text}',data['name']);
$(domStrings.supplierSelect).append($.parseHTML(模板));
$(domStrings.supplierSelect).selectPicker('refresh');
//修理工
})
.catch(错误=>console.log(错误))
});
但这是行不通的。我的代码有什么问题 首先检查传入数据的格式是否正确。为此,我将重点介绍在接收新数据后生成
选项
标记的技术。当前正在设置一个变量,每次获取数据时使用一个字符串,将其替换为新值,并使用parseHTML
附加到DOM。可以使用ES6字符串文字和$
方法减少它:
$select.append($(`<option value="${value}">${text}</option>`));
$select.append($(`${text}');
我给出了一个简单的示例概念:您在尝试获取数据后是否收到了一些堆栈跟踪?在示例中指定正在实现引导选择也是很有用的。我正确地获取了数据,问题是当我将项目添加到选择器中时,该项目是一个输入错误,而不是“selectPicker”,我应该使用“selectpicler”,并将类名更改为id