如果我的术语不正确,我道歉 - 这绝对不是我的专业领域.
我希望<select>从json文件中创建一个列表,并<optgroup>通过键对s中的条目进行分组.我已经成功地列出了select中的所有条目,但是不知道如何在其键下循环并嵌套项.
我的JSON看起来像这样:
[
{
"Type" : "Overdrive",
"Brand" : "Chase Bliss",
"Name" : "Brothers",
"Width" : 2.75,
"Height" : 4.77,
"Image" : "public/images/pedals/chasebliss-brothers.png"
}
]
Run Code Online (Sandbox Code Playgroud)
这是我如何呈现<select>:
window.RenderPedals = function(pedals){
for(var i in pedals) {
var $pedal = $("<option>"+ pedals[i].Brand + " " + pedals[i].Name +"</option>").attr('id', pedals[i].Name.toLowerCase().replace(/\s+/g, "-").replace(/'/g, ''));
$pedal.data('width', pedals[i].Width);
$pedal.data('height', pedals[i].Height);
$pedal.data('height', pedals[i].Height);
$pedal.data('image', pedals[i].Image);
$pedal.appendTo('.pedal-list');
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是这个标记:
<select>
<optgroup label="Chase Bliss">
<option data-width="..." data-height="..." data-image="...">Chase Bliss Brothers</option>
</optgroup>
</select>
Run Code Online (Sandbox Code Playgroud)
谁能指出我正确的方向?
您可以使用对象解构来获取当前对象的属性,无需for..in循环,创建一个属性设置为、 附加到、 附加到 的<optgroup>元素。检查属性设置为 的元素是否存在,如果存在,则将 附加到该元素,否则将新元素附加到设置为新元素。label"Brand"<option><optgroup><optgroup><select><optgroup>labelBrandtrue<option><optgroup><optgroup><select>html<option>
var data = [{
"Type": "Overdrive",
"Brand": "Chase Bliss",
"Name": "Brothers",
"Width": 2.75,
"Height": 4.77,
"Image": "public/images/pedals/chasebliss-brothers.png"
}
, {
"Type": "Underdrive",
"Brand": "Bliss Chase",
"Name": "Sisters",
"Width": 5.72,
"Height": 7.74,
"Image": "public/images/pedals/chasebliss-sisters.png"
}
, {
"Type": "Throughdrive",
"Brand": "Bliss Chase",
"Name": "Cousins",
"Width": 2.75,
"Height": 4.74,
"Image": "public/images/pedals/chasebliss-cousins.png"
}
];
window.RenderPedals = function(pedals) {
var {Type, Brand, Name, Width, Height, Image} = pedals;
var option = $("<option>", {
text: `${Brand} ${Name}`,
id: Name.toLowerCase()
.replace(/(\s+)|(['"])/g, (m, p1, p2) => p1 ? "-" : ""),
data: {
width: Width,
height: Height,
image: Image
}
});
if ($("optgroup").is(`[label="${Brand}"]`)) {
$(`optgroup[label="${Brand}"]`).append(option);
} else {
$("<optgroup>", {
label: Brand,
html: option
}).appendTo(".pedal-list");
}
}
data.forEach(RenderPedals);Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<select class="pedal-list"></select>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |