function main() {
workMenu("leftVerticalMenu");
}
function log(obj) {
console.log(obj);
}
function workMenu(id) {
var menuContainer = document.getElementById(id).children[0];
closeListsNodes(menuContainer);
}
function closeListsNodes(container) {
var object = container.getElementsByTagName("li");
for (var i = 0; i < object.length; i++) {
var need = object[i].getElementsByTagName("ul");
for (var j = 0; j < need.length; j++) {
need[j].style.display = "none";
need[j].id = i.toString() + j.toString();
need[j].onclick = function () {
hideshow(need[j].id);
};
}
}
}
function hideshow(id) {
var need = document.getElementById(id);
if (need.style.display == 'none') {
need.style.display = 'block';
} else {
need.style.display = 'none';
}
}
此代码以最小化模式创建一个列表并输入 ID。但是代码不会将onclick event handler
s 添加到 html 页面。我尝试使用代码示例,但不工作。如何在不使用 jQuery 的情况下实现它?
<body onload="main();">
<div id="leftVerticalMenu">
<ul>
<li>
<a href="#">item 1</a>
<ul>
<li>
<a href="#">item 11</a>
<ul>
<li>
<a href="#">item 111</a>
</li>
<li>
<a href="#">item 112</a>
</li>
</ul>
</li>
<li>
<a href="#">item 12</a>
</li>
</ul>
</li>
<li>
<a href="#">item 2</a>
<ul>
<li>
<a href="#">item 21</a>
</li>
<li>
<a href="#">item 22</a>
</li>
</ul>
</li>
</ul>
</div>
</body>