我有 ID 和名称的字符串,用 ^(ID 和名称之间)和 ; 分隔。 (组间)例如
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
我需要得到这样的东西
$('#1').html('<option value="1">John Smith</option><option value="2">Sophia Williams</option><option value="3">Emily Johnson</option>');
我尝试了循环但卡住了:
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var a = string.split(";"),
i;
for (i = 0; i < a.length; i++){
if (a[i] !== ""){
var b = a[i].split("^"),
i2;
for (var i2 = 0; i2 < b.length; i++) {
var name = b[i2];
console.log(name);
}
}
}
我不确定这是不是好方法
最佳答案
使用Option()
new Option(text, value, defaultSelected, selected)
var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;"
var options = string.split(';').map(i => {
return new Option(...i.split('^').reverse())
})
$('#1').html(options)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="1"></select>
关于Javascript:在循环中按循环分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60849596/