gpt4 book ai didi

javascript - 动态下拉 jQuery 内联错误

转载 作者:行者123 更新时间:2023-11-29 18:55:30 33 4
gpt4 key购买 nike

我正在尝试使用数组值创建动态下拉列表,但值在 option 中内联附加

<body onload="getdata()">
<select class="form-control" id="focusedinput" name="sBranchName" required>
<option name="sBranchName" id="branch_list" ></option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>

<script>
function getdata () {
var data =['rajkot','surat','delhi']
var mySelect = $('#branch_list');
for(let value of data){
console.log(value)
mySelect.append("<option>" + value + "</option>")
}
};
</script>
</body>

谁能推荐正确的方法?

最佳答案

看到这一行:

mySelect.append("<option>" + value + "<option>")

您缺少一个 / .

您还附加到 option而不是 select .尝试选择 select相反:

$('#focusedinput').append("<option>" + value + "</option>")

function getdata() {
const data = ['rajkot', 'surat', 'delhi']
const mySelect = $('#focusedinput');
data.forEach((value) => {
mySelect.append("<option>" + value + "</option>");
});
}

getdata();
<select class="form-control" id="focusedinput" name="sBranchName" required>
<option name="sBranchName" id="branch_list" ></option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于javascript - 动态下拉 jQuery 内联错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616934/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com