使用 JavaScript 导航到另一个页面时,如何保留子菜单的打开/关闭状态?我尝试使用此代码在导航到另一个页面时保持菜单状态,但它对我不起作用。也许我错过了什么。
<ul class="catMenuItem">
<li><a style="background-image: url("images/triangle_down.gif");" href="#"
class="titleTriangle"><span>cat1</span></a></li>
<li style="display: block;" class="catSubMenu">
<a href="?cat=2">sub 1-2</a> (0)
<a href="?cat=7">sub 1-3</a> (2)
<a href="?cat=8">sub 1-4</a> (0)
<a href="?cat=9">sub 1-5</a> (0)
</li>
</ul>
<ul class="catMenuItem">
<li>
<a href="#" class="titleTriangle"><span>cat2</span></a>
</li>
<li style="display: none;" class="catSubMenu">
<a href="?cat=3">sub 2-1</a> (0)<br>
<a href="?cat=4">sub 2-2</a> (0)<br>
<a href="?cat=5">sub 2-3</a> (0)<br>
<a href="?cat=6">sub 2-4</a> (1)<br>
<br>
</li>
</ul>
var prevCat;
function menu(newCat) {
var mens;
var anchors;
if (prevCat) {
mens = prevCat.parentNode.getElementsByTagName('li')[0];
anchors = mens.getElementsByTagName('a')[0].style.backgroundImage = 'url(images/triangle_right.gif)';
prevCat.style.display = 'none';
}
if (newCat != prevCat) {
mens = newCat.parentNode.getElementsByTagName('li')[0];
anchors = mens.getElementsByTagName('a')[0].style.backgroundImage = 'url(images/triangle_down.gif)';
newCat.style.display = 'block';
prevCat = newCat;
} else {
prevCat = null;
}
}
onload = function () {
var menus = document.getElementsByTagName('ul');
for (var a = 0, x = menus.length; a < x; a++) {
if (menus[a].className === 'catMenuItem') {
menus[a].getElementsByTagName('li')[0].getElementsByTagName('a')[0].onclick = function () {
menu(this.parentNode.parentNode.getElementsByTagName('li')[1]);
}
menus[a].getElementsByTagName('li')[1].style.display = 'none';
}
}
}