作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个数组。数组中的元素表示菜单元素。我想根据我选择的菜单项创建“面包屑”。但是,它在工作时会在 3 个深度后动态提供错误。
// My Array
const menuArray = [{
"label": "Dashboard"
},
{
"label": "Products",
"items": [{
"label": "All Products"
},
{
"label": "New Product"
},
{
"label": "Product Categories"
}
]
},
{
"label": "Posts",
"items": [{
"label": "All Posts"
},
{
"label": "New Post"
},
{
"label": "Post Categories"
}
]
},
{
"label": "Sliders"
},
{
"label": "Settings",
"items": [{
"label": "General Settings"
},
{
"label": "User",
"items": [{
"label": "Your Profile"
},
{
"label": "Edit Profile"
}
]
},
{
"label": "Social Settings"
},
{
"label": "Link Settings"
}
]
}
];
// The function I experiment with
writeParent(event, arr) {
let ct = 0;
let found = false;
let parentsLine = [];
arr.some((e) => {
parentsLine = [];
let curr = e;
for (curr; curr.items != null; curr = curr.items[0]) {
if (event.label == curr.label) {
found = true;
return true;
}
parentsLine.push(curr.label);
}
if (event.label == curr.label) {
found = true;
return true;
}
});
if (found) {
return parentsLine;
} else {
return 'ERR: elm not found';
}
}
console.log(writeParent({
"label": "Edit Profile"
}, menuArray));
比如我选择的元素是;
{
"label": "New Post"
}
我要得到;
[
{
"label": "Posts"
},
{
"label": "New Post"
}
]
或者
如果我选择的元素是;
{
"label": "Edit Profile"
}
我要得到;
[
{
"label": "Settings"
},
{
"label": "User"
},
{
"label": "Edit Profile"
}
]
我不知道如何找到所选元素的父元素。我该怎么做?
最佳答案
我已经解决了这个问题。
menuArray = [{
"label": "Dashboard"
},
{
"label": "Products",
"items": [{
"label": "All Products"
},
{
"label": "New Product"
},
{
"label": "Product Categories"
}
]
},
{
"label": "Posts",
"items": [{
"label": "All Posts"
},
{
"label": "New Post"
},
{
"label": "Post Categories"
}
]
},
{
"label": "Sliders"
},
{
"label": "Settings",
"items": [{
"label": "General Settings"
},
{
"label": "User",
"items": [{
"label": "Your Profile"
},
{
"label": "Edit Profile"
}
]
},
{
"label": "Social Settings"
},
{
"label": "Link Settings"
}
]
}
];
function find(array, event) {
if (typeof array != 'undefined') {
for (let i = 0; i < array.length; i++) {
if (array[i].label == event.label) return [event.label];
let a = this.find(array[i].items, event);
if (a != null) {
a.unshift(array[i].label);
return a;
}
}
}
return null;
}
console.log(find(menuArray, { "label": "Edit Profile" }));
关于javascript - 被选元素在哪些元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58400896/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!