JS using onclick event on li to display block

2019-07-23 16:41发布

问题:

HTML:

<script>function dropdown()
{        console.getElementById("").style.display="block";
}</script>
<div id="dropdown">
    <ul>
        <li onclick="dropdown()"><a>Menu</a>
             <ul id="Menuitems">
                 <li><a href="">item 1</a> </li>
                 <li><a href="">item 2</a> </li>
                 <li><a href="">item 3</a> </li>
            </ul>
        </li>
    </ul>
</div>    

Css:

#dropdown ul{
 display: block; 
}
#dropdown ul li {
     display: block;
     background-color: #558c89;
     color: #ffffff; 
}
#dropdown ul li ul {
     display: none; 
}
#dropdown ul li:hover > ul { /*this is what the onclick event should do*/
     display: block; 
}

The onclick should start the function "dropdown()" which needs to: "display: block;" on #dropdown ul li

回答1:

You're missing the list ID and you're calling the selector on the console (when you want to be selecting on the document).

<script>
function dropdown()
{        
    document.getElementById("Menuitems").style.display="block";
}
</script>
<div id="dropdown">
    <ul>
        <li onclick="dropdown()"><a>Menu</a>
             <ul id="Menuitems">
                 <li><a href="">item 1</a> </li>
                 <li><a href="">item 2</a> </li>
                 <li><a href="">item 3</a> </li>
            </ul>
        </li>
    </ul>
</div>  

JSFiddle: http://jsfiddle.net/tmaB9/



回答2:

Try:

<li onClick="dropDown(this);">

This is important, so your function knows which element you clicked on. Then...

function dropDown(li) {
    var submenu = li.getElementsByTagName('ul')[0];
    if( submenu) {
        submenu.style.display = submenu.style.display == "block" ? "" : "block";
    }
}

This will toggle the visibility of the submenu :)



回答3:

here is a quick example of what i think you want (provided you can use JQuery):

    $(document).ready(function () {
        $('#dropdown ul li').on('click', function dropdown() {
            //console.getElementById("").style.display = "block";
        });
    });

<div id="dropdown" class="dropdown">
    <ul>
        <li>menu 1</li>
        <li>menu 2</li>
        <li>menu 3</li>
        <li>menu 4</li>
    </ul>
</div>