[英]jQuery code to dynamically build a collapsible UL from JSON strings
我是 JavaScript 和 jQuery 世界的新手。
有人可以幫助我構建一個從 JSON 數組返回動態可折疊“ul”的 jQuery 函數。 我嘗試了不同的解決方案,如來自各種代碼存儲庫的 jstree、jsonview、renderjson 和一些堆棧溢出答案,但似乎沒有任何適用於我的用例。
這是示例 JSON 數組:
[
{
"name": "forwarding_options",
"type": {
"fields": [
{
"metadata": {},
"name": "PICKUP_SERVICE",
"nullable": true,
"type": "string"
},
{
"metadata": {},
"name": "TWO_MAN_DELIVERY",
"nullable": true,
"type": "string"
}
],
"type": "struct"
}
},
{
"name": "fulfillment_time",
"type": "string"
},
{
"name": "merchant_delivery_text",
"type": "string"
},
{
"name": "status",
"type": "string"
},
{
"name": "type",
"type": "string"
}
]
我需要如下鏈接所示的內容,以便我可以附加到表格 td 標簽:
希望這對你有幫助。
var jsonarr = [{ "name": "forwarding_options", "type": { "fields": [{ "metadata": {}, "name": "PICKUP_SERVICE", "nullable": true, "type": "string" }, { "metadata": {}, "name": "TWO_MAN_DELIVERY", "nullable": true, "type": "string" } ], "type": "struct" } }, { "name": "fulfillment_time", "type": "string" }, { "name": "merchant_delivery_text", "type": "string" }, { "name": "status", "type": "string" }, { "name": "type", "type": "string" } ]; var ret_html = ''; jQuery.each(jsonarr, function(index, mainitem) { ret_html += '<li>' + mainitem['name'] + '</li>'; jQuery.each(mainitem, function(index, items) { if (items['fields']) { ret_html += '<li><span class="caret">Fields</span>'; ret_html += '<ul class="nested">'; jQuery.each(items['fields'], function(index, tree) { ret_html += '<li>' + tree['name'] + '</li>'; }); ret_html += '</ul>' ret_html += '</li>'; } }); }); jQuery('#returnresult').append(ret_html); var toggler = document.getElementsByClassName("caret"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener("click", function() { this.parentElement.querySelector(".nested").classList.toggle("active"); this.classList.toggle("caret-down"); }); }
/* Remove default bullets */ ul, #myUL { list-style-type: none; } /* Remove margins and padding from the parent ul */ #myUL { margin: 0; padding: 0; } /* Style the caret/arrow */ .caret { cursor: pointer; user-select: none; /* Prevent text selection */ } /* Create the caret/arrow with a unicode, and style it */ .caret::before { content: "\\25B6"; color: black; display: inline-block; margin-right: 6px; } /* Rotate the caret/arrow icon when clicked on (using JavaScript) */ .caret-down::before { transform: rotate(90deg); } /* Hide the nested list */ .nested { display: none; } /* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */ .active { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="myUL"> <li><span class="caret">Json array</span> <ul id="returnresult" class="nested"> </ul> </li> </ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.