问题描述
我正在使用引导选择插件.我正在填充一个动态创建的选择,如下所示:
I'm using the bootstrap select plugin. I am populating a dynamically created select like so:
var select = $('<select/>', {
'class':"selectpicker"
}).selectpicker();
for (var idx in data) {
if (data.hasOwnProperty(idx)) {
select.append('<option value=' + data[idx].id+ '>' + data[idx].Text+ '</option>');
}
}
select.selectpicker('refresh');
数据很好并且创建了一个选择,它无法识别我试图创建的引导选择器.在同一页面上有一个我不能动态创建的选择,它运行良好.
The data is fine and a select is created, it is not recognizing the bootstrap selectpicker i am trying to create. I have a select on the same page that I do not create dynamically and it works fine.
<select class="selectpicker">
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
$('.selectpicker').selectpicker();
如何动态创建引导选择?谢谢.
How do I dynamically create a bootstrap select? Thanks.
推荐答案
在调用selectpicker()
之前,需要将创建的<select />
附加到DOM上,如下所示:
You need to append the <select />
you create to the DOM before calling selectpicker()
on it, something like this:
var $select = $('<select/>', {
'class':"selectpicker"
});
for (var idx in data) {
$select.append('<option value=' + data[idx].id + '>' + data[idx].Text + '</option>');
}
$select.appendTo('#myElement').selectpicker('refresh');
请注意append()
的使用以及hasOwnProperty
的删除-您已经在遍历对象的属性,因此方法调用是多余的.
Note the use of append()
, and also the removal of hasOwnProperty
- you're already looping through the properties of the object so that method call is redundant.
这篇关于动态创建引导选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!