gpt4 book ai didi

javascript - 从对象数组创建模拟分层选择框

转载 作者:行者123 更新时间:2023-11-27 22:32:04 25 4
gpt4 key购买 nike

我想创建一个选择框并使用我的平面 JSON 数据显示项目及其深度。下图与 Joomla CMS 在分层类别中所做的相同,但使用 PHP。

Joomla CMS hierarchical categories

我的示例数据如下(请注意,深度是无限的):

[{
"id": 1,
"parent": "0",
"text": "Doctors"
}, {
"id": 2,
"parent": "0",
"text": "Clinics"
}, {
"id": 3,
"parent": 1,
"text": "General doctors"
}, {
"id": 4,
"parent": 1,
"text": "Experts"
}, {
"id": 5,
"parent": 4,
"text": "Children diseases specialist"
}, {
"id": 6,
"parent": 4,
"text": "Otorhinolaryngology"
}]

我编写了以下代码,并通过调用 Data.createTreeOptions(items); 使用它,它正在工作,但我得到的是按原始数组项排序的选项列表。我希望项目以父 - 子顺序加载,如图所示。

var Data = {
createTreeOptions: function (items) {
if (!items.length)
return '';
var html = '', children = [], l;

$.each(items, function () {
l = (typeof children[this.parent] !== "undefined") ? children[this.parent] : [];
l.push(this);
children[this.parent] = l;
});

var tree = Data.treeRecurse(0, '', [], children, 0);
$.each(tree, function () {
if (typeof this.id !== "undefined")
html += '<option value="' + this.id + '" data-parent="' + this.parent + '">' + this.treemenu + '</option>';
});
return html;
}
, treeRecurse: function (id, indent, list, children, level) {
if (typeof children[id] !== "undefined" && children[id]) {
$.each(children[id], function () {
var v = this;
var id = v.id;
if (v.parent === 0)
text = v.text;
else
text = '|_ ' + v.text;

list[id] = v;
list[id].treemenu = indent + text;
list[id].children = (typeof children[id] !== "undefined") ? children[id].length : 0;
level++;
list = Data.treeRecurse(id, indent + ' -', list, children, level);
});
}
return list;
}
}

最佳答案

在您的具体情况下,您可以这样创建和使用 jQuery 对象:

var items = [{
"id": 1,
"parent": "0",
"text": "Doctors"
}, {
"id": 2,
"parent": "0",
"text": "Clinics"
}, {
"id": 3,
"parent": 1,
"text": "General doctors"
}, {
"id": 4,
"parent": 1,
"text": "Experts"
}, {
"id": 5,
"parent": 4,
"text": "Children diseases specialist"
}, {
"id": 6,
"parent": 4,
"text": "Otorhinolaryngology"
}];
var imagine = $('<div><div class="hierarchy-0"></div></div>');
$.each(items, function(i, item) {
var parent = imagine.find('.hierarchy-'+item.parent);
parent.append('<div class="hierarchy-'+item.id+'"><span>'+item.text+'</span></div>');
});
function findChildren(elem, indent) {
elem.children('div').each(function(c, child) {
selectHtml += '<option>'+'-'.repeat(indent)+$(child).children('span').text()+'</option>';
findChildren($(child), indent+1);
});
};
var selectHtml = '';
findChildren(imagine.find('.hierarchy-0'), 0);
$('select').html( selectHtml );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>

同时在 JSFiddle .

但是,我相信您会得到另一种更好的方法:)

关于javascript - 从对象数组创建模拟分层选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39478413/

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