Axel Richter: Javascriptmenü mit verschachtelten Listen

Beitrag lesen

Hallo,

Meine JS Funktion:

activateMenu = function(nav) {

if (document.all && document.getElementById(nav).currentStyle) {

var navroot = document.getElementById(nav);

/* lade alle listenpunkte /
  var lis=navroot.getElementsByTagName("LI");
  for (i=0; i<lis.length; i++) {
   /
hat der nachfolgende li ein untermenue ? <ul> /
   var next = i + 1;
   if(lis[next].lastChild.tagName=="UL"){
    /
assign the function to the current LI /
    lis[i].onmouseover=function() {
     /
display the inner menu for next li /
     lis[next].firstChild.style.display="block";
    }
    /
assign the function to the current LI /
    lis[i].onmouseout=function() {
     /
hide */
     lis[next].firstChild.style.display="none";
    }
   }
  }

}

}

Aus welchen Quellen ist das zusammenkopiert? Mit .firstChild und .lastChild wirst Du im IE nur dann die richtigen Elemente treffen, wenn Du immer eine bestimmte HTML-Struktur einhältst. Das ist also sehr unflexibel. Besser ist, die Elemente mit getElementsByTagName zu holen.  
  
Außerdem würde ich IE-Only-JavaScript besser in einem Conditional Comment aufgehoben finden.  
  
Beispiel:  
  
~~~html
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"  
        "http://www.w3.org/TR/html4/strict.dtd">  
<html>  
<head>  
<title>Titel</title>  
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">  
<!--[if IE]>  
<script type="text/javascript">  
function activateMenu(nav) {  
 var navroot = document.getElementById(nav);  
  
 /* lade alle listenpunkte */  
 var lis=navroot.getElementsByTagName("LI");  
  
 for (i=0; i<lis.length; i++) {  
  /* hat der nachfolgende LI ein untermenue? */  
  if((lis[i].getElementsByTagName("UL")).length) {  
   /* assign the function to the current LI */  
   lis[i].onmouseover=function() {  
    /* display the inner menu for next li */  
    this.getElementsByTagName("UL")[0].style.display="block";  
   }  
   /* assign the function to the current LI */  
   lis[i].onmouseout=function() {  
    /* hide */  
    this.getElementsByTagName("UL")[0].style.display="none";  
   }  
  }  
 }  
}  
window.onload = function() {activateMenu("nav");};  
</script>  
<![endif]-->  
</head>  
<body>  
<ul id="nav">  
  <li><a href="#">Punkt1</a></li>  
  <li><a href="#">Punkt2</a>  
      <ul>  
        <li><a href="#" >Punkt2.1</a>  
            <ul>  
              <li><a href="#" >Punkt2.1.1</a></li>  
            </ul>  
        </li>  
      </ul>  
  </li>  
  <li><a href="#">Punkt3</a>  
      <ul>  
        <li><a href="#" >Punkt3.1</a></li>  
      </ul>  
  </li>  
  <li><a href="#">Punkt4</a></li>  
</ul>  
</body>  
</html>  

viele Grüße

Axel