gpt4 book ai didi

javascript - 通过 jQuery 对选项值进行分组

转载 作者:行者123 更新时间:2023-11-29 21:13:08 24 4
gpt4 key购买 nike

如何对选项值进行分组。这是我的 HTML

<select id="kota"> </select>

和我的 JS

var $sel = $('select#kota');
availableTags.forEach(function(tag) {
$sel.append('<optgroup label="'+tag.area+'"><option value="'+tag.stationcode +'">'+ tag.label +'</option></optgroup>');
});

我想为 Jakarta 和万隆分开“标签”。对 body 有帮助吗?或建议?这是我在 jsfiddle 中的完整代码。 https://jsfiddle.net/dedi_wibisono17/u1be7gkq/7/

我想要这样的期望 enter image description here

谢谢

最佳答案

这个解决方案怎么样。希望对您有所帮助:)!

$(document).ready(function(){

var availableTags = [{
label: "Bandung - Bandung (BD)",
area: "Bandung",
station: "Bandung",
stationcode: "BD"
}, {
label: "Bandung - Cicalengka (CCL)",
area: "Bandung",
station: "Cicalengka",
stationcode: "CCL"
}, {
label: "Bandung - Cikadongdong (CD)",
area: "Bandung",
station: "Cikadongdong",
stationcode: "CD"
}, {
label: "Jakarta - Gambir (GMR)",
area: "Jakarta",
station: "Gambir",
stationcode: "GMR"
}, {
label: "Jakarta - Jakarta Kota (JAKK)",
area: "Jakarta",
station: "Jakarta Kota",
stationcode: "JAKK"
}, {
label: "Jakarta - Jatinegara (JNG)",
area: "Jakarta",
station: "Jatinegara",
stationcode: "JNG"
}];

var bandungArray = [];
var jakartaArray = [];
var output1 = [];
var output2 = [];

for(var i = 0 ; i < availableTags.length; i++){
if((availableTags[i].label).indexOf("Bandung") !== -1){
bandungArray.push(availableTags[i]);
}
else{
jakartaArray.push(availableTags[i]);
}
}

bandungArray.forEach(function(tag) {
output1.push('<option value="'+ tag.stationcode +'">'+ tag.label +'</option>');
});
jakartaArray.forEach(function(tag) {
output2.push('<option value="'+ tag.stationcode +'">'+ tag.label +'</option>');
});

$('#kota').html("<optgroup label='Bandung'>"+output1.join('') + "<optgroup label='Jakarta'>"+output2.join(''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id="kota">
</select>

关于javascript - 通过 jQuery 对选项值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40755303/

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