我想创建一个选择框下拉菜单。最初的选择框将没有任何选项,它应该仅显示选择。 单击选择框时,它将迭代列表并将每个选项添加到该选择框。
我正在尝试使用以下代码-
$(".droptest").click(function(e){
e.preventDefault();
var listDrop = [{"chdk74":"hdk73","hiphdk":"hiphdk","hpghdk":"hpghdk","ihdk":"ihdk","sdg74":"sdg74"}];
var dropDownlist = JSON.parse(listDrop);
var options = "";
$.each(dropDownlist, function(key,value) {
options += "<option name=" + value +" id=" + value +" value="+value+"> "+ value +" </option>";
});
$(".DomainDrop").html(options);
});
<div class="droptest">
<select class="DomainDrop tet" id="DomainDropCreate" name="DomainDrop" required>
<option name="" value="">Select Domain</option>
</select>
</div>
答案 0 :(得分:2)
您要做的是从[]
中删除listDrop
,然后使用$.each(listDrop, function(key, value) {
演示
$(".droptest").mousedown(function(e) {
var listDrop = {
"chdk74": "hdk73",
"hiphdk": "hiphdk",
"hpghdk": "hpghdk",
"ihdk": "ihdk",
"sdg74": "sdg74",
};
var options = "";
$.each(listDrop, function(key, value) {
options += "<option name=" + value + " id=" + value + " value=" + value + "> " + value + " </option>";
});
if ($(".DomainDrop option").length < 2) {
$(".DomainDrop").html(options);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="droptest">
<select class="DomainDrop tet" id="DomainDropCreate" name="DomainDrop" required>
<option name="" value="">Select Domain</option>
</select>
</div>
如Freedomn-m所说,将click
更改为mousedown
并删除e.PreventDefault()
,然后一切正常。