Javascript 如何设置js菜单对象的活动属性?
我创建了一个指向我的网站的菜单导航,该菜单很简单,由我的对象创建:Javascript 如何设置js菜单对象的活动属性?,javascript,Javascript,我创建了一个指向我的网站的菜单导航,该菜单很简单,由我的对象创建: const routes = [ { text: "im foo", path: "foo", active: null, children: [ { text: "im foo", path: "baz", active: null, c
const routes = [
{
text: "im foo",
path: "foo",
active: null,
children: [
{
text: "im foo",
path: "baz",
active: null,
children: [
{
text: "im foo",
path: "baz",
active: null,
children: [{ text: "im foo", path: "daz", active: null }]
}
]
}
]
},
{
text: "im A",
path: "a",
active: null,
children: [
{
text: "im B",
path: "b",
active: null,
children: [
{
text: "im c",
path: "c",
active: null
},
{
text: "im d",
path: "d",
active: null
}
]
}
]
}
];
此菜单具有折叠行为。这意味着我可以打开和关闭菜单中的项目,例如:
当active
属性设置为true时,我会给出一个类来打开菜单
我的问题是如何根据给定的url设置active
属性?例如,我的url是foo/bar/baz/daz
,因此我需要找到daz
的位置并向上移动
问题是我如何做“上升”?我不知道如何实现这一点。我想您应该在routes数组中循环,找到活动节点,然后向其中添加类?下面是查找节点的代码。希望这能有所帮助
findNode(nodes: Array<any>) {
let nodesArray = JSON.parse(JSON.stringify(nodes));
nodesArray.forEach(rootNode => {
let queue = [];
queue.push(rootNode);
while (queue.length > 0) {
let nodeObj = queue.shift();
// TODO: this is the place for your logic to find the node
if (nodeObj && nodeObj.children) {
nodeObj.children.forEach(element => {
queue.push(element);
});
}
}
});
}
findNode(节点:数组){
让nodesArray=JSON.parse(JSON.stringify(nodes));
nodesArray.forEach(rootNode=>{
让队列=[];
push(rootNode);
while(queue.length>0){
让nodeObj=queue.shift();
//TODO:这是逻辑查找节点的地方
if(nodeObj&&nodeObj.children){
nodeObj.children.forEach(元素=>{
push(元素);
});
}
}
});
}
const路由=[
{
文字:“imfoo”,
路径:“foo”,
活动:空,
儿童:[
{
文字:“imfoo”,
路径:“baz”,
活动:空,
儿童:[
{
文字:“imfoo”,
路径:“baz”,
活动:空,
子项:[{文本:“im foo”,路径:“daz”,活动:null}]
}
]
}
]
},
{
文字:“我是一个”,
路径:“a”,
活动:空,
儿童:[
{
文字:“im B”,
路径:“b”,
活动:空,
儿童:[
{
文字:“即时通讯”,
路径:“c”,
活动:空
},
{
文字:“imd”,
路径:“d”,
活动:空
}
]
}
]
}
];
功能设置激活(路由、路径){
如果(paths.length==0)返回true;//匹配所有
如果(!routes)返回false;//不匹配所有
const path=path.shift();
const matchRoute=routes.find(i=>i.path==path);
如果(匹配路线){
const preState=matchRoute.active;
const isMatchAll=setActive(matchRoute.children,paths);
matchRoute.active=isMatchAll | | preState;
返回isMatchAll;
}
//没有找到路线
返回false;
}
//好的,用active true标记路径
setActive(路线“foo/baz/baz/daz.”拆分(“/”);
//没有火柴,保持原样
//setActive(路线“foo/baz/baz/dz.”拆分(“/”);
控制台日志(路由)代码>循环查找第一部分foo并设置为活动;然后通过它的子循环查找并设置为真等等,如果它不存在显示错误?问题是什么?您尝试过什么?谢谢,但如果找到,我想用active true标记路径,而不仅仅是根。我现在明白您的意思,可以使用回溯算法来解决此问题。