gpt4 book ai didi

javascript - JSON结果值作为JavaScript/jQuery中的键

转载 作者:行者123 更新时间:2023-12-03 06:55:35 24 4
gpt4 key购买 nike

我有一个JSON结果,我想在其中创建一个 Accordion 菜单,我想要一个类似结果的值作为那些相​​似行的标题,请检查以下内容以查看我做了什么。
假设我有下面的JSON对象

var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]
我的JS代码的相关部分如下:
 var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}

list += '<a href="#" class="list-group-item">' + label + "</a>";

}
list += "</div>";
myUL.append(list);
我的HTML div的一部分
<div class="list-group panel" id="accordion"></div>
结果我现在得到
enter image description here
我期望什么
enter image description here

最佳答案

代码缩进可以在这种情况下提供帮助。最后两行应该在循环内,这样代码才有意义。在每次迭代中,必须关闭div并将代码添加到myUL:

var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}]


var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
var list = '';
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}

list += '<a href="#" class="list-group-item">' + label + "</a>";
list += "</div>";
myUL.append(list);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-group panel" id="accordion"></div>

另外,您需要定义 list

关于javascript - JSON结果值作为JavaScript/jQuery中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64947884/

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