我的JavaScript需要一些帮助,因为它在我测试时表现得很奇怪。问题是,当我点击绿色阴影区域的 P1,P2,Cello,C2,C1 的最左侧时,我的树会折回到 Item 不会发生。如果我点击 parker 或 cell 或item,它应该有点像,它的子部分将被关闭或打开。
var dataSource = ({
"Pen": ({
"Parker": ({
"P1": ({}),
"P2": ({})
}),
"Cello": ({
"C2": ({}),
"C1": ({})
})
})
}),
Objectkeys = function(obj){
a = []
for(var prop in obj){
if (obj.hasOwnProperty(prop)) {
a.push(prop);
}
};
return a;
},
traverseObject = function (obj) {
var ul = document.createElement("ul"),
li,span;
for (var prop in obj) {
li = document.createElement("li");
li.appendChild(document.createTextNode(prop));
li.style.backgroundColor = "green";
li.onclick = function(e) {
var classNames = this.className;
if (classNames.indexOf("hidden") == -1) {
this.className += "hidden";
} else {
this.className = this.className.replace("hidden", "");
}
if (!e)
e = window.event;
if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.cancelBubble = true;
}
}
if (typeof obj[prop] == "object" && Objectkeys(obj[prop]).length) {
li.appendChild(traverseObject(obj[prop]));
} else {
li.className += "leaf";
}
ul.appendChild(li);
console.log(ul);
}
return ul;
},
sortedObject = function (obj) {
document.getElementById("dvList2").innerHTML = "";
var ul = document.createElement("ul"),
li,keys = Objectkeys(obj).sort();
for (prop in keys) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(keys[prop]));
li.onclick = function(e) {
var classNames = this.className;
if (classNames.indexOf("hidden") == -1) {
this.className += "hidden";
} else {
this.className = this.className.replace("hidden", "");
}
if (!e)
e = window.event;
if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.cancelBubble = true;
}
}
if (typeof obj[keys[prop]] == "object" && Objectkeys(obj[keys[prop]]).length) {
li.appendChild(sortedObject(obj[keys[prop]]));
} else {
li.className += "leaf";
}
ul.appendChild(li);
console.log(ul);
}
return ul;
};
window.onload = function () {
document.getElementById("dvList1").appendChild(traverseObject(dataSource));
document.getElementById("hlGSL").onclick = function(){document.getElementById("dvList2").appendChild(sortedObject(dataSource));}
}
谢谢
答案 0 :(得分:0)
您的li.onclick = function(e) { }
正在注册嵌套树的最外层<li>
元素。添加语句以确保用户单击的内容实际上是子节点。
...
li.style.backgroundColor = "green";
li.onclick = function(e) {
// Is the parent's parent the dvList1 <div>?
if (li.parent.parent.id == "dvList1") {
// Do nothing
} else {
// If it isn't, do the rest of the code
var classNames = this.className;
if (classNames.indexOf("hidden") == -1) {
this.className += "hidden";
} else {
this.className = this.className.replace("hidden", "");
}
...