我正在使用 select2 进行搜索和选择选项。当我通过 jquery 添加该代码时,它不起作用。我认为myselect
类没有调用。但是如果正常添加这些相同的代码(html,不使用 jquery),它工作正常。
输出:-select2 使用普通 HTML:工作
输出:-select2,当使用 jquery html() 方法时:不工作
$("#menu").html("<select class='myselect form-control' id='class-in-charge' style=' width:100%;' ><option hidden selected disabled></option><option>Sahal EV</option><option>Muhammed Rahil</option><option>Venmuka Jishwanth</option><option>Freejin Ram Pacha</option></select>");
任何人都可以帮忙。提前致谢。
您需要select
在将其添加到 DOM 后对其进行初始化。
let select = document.createElement('select')
select.className = 'myselect form-control'
select.id = 'class-in-charge'
select.innerHTML = '<option hidden selected disabled></option><option>Sahal EV</option><option>Muhammed Rahil</option><option>Venmuka Jishwanth</option><option>Freejin Ram Pacha</option>'
menu.appendChild(select)
$(select).select2()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<div id="menu"></div>
这是一个仅使用 jQuery 的解决方案(尽管我更愿意在没有必要的情况下不使用 jQuery):
$("#menu").html("<select class='myselect form-control' id='class-in-charge'><option hidden selected disabled></option><option>Sahal EV</option><option>Muhammed Rahil</option><option>Venmuka Jishwanth</option><option>Freejin Ram Pacha</option></select>");
$('#class-in-charge').select2()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<div id="menu"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句