简体   繁体   中英

Dynamic <ul> and <li> on hover in <ul> show <li>

I have 3 <ul> and each <ul> element have 1 hidden <li style="display:none;"> hover on 1 <ul> i want to show only <li> of which that <ul> is hover

Problem is that when i hover on 1 <ul> element it will hover on all 3 <ul> element and display all <li> element.

Below is my code

<html>
<head>
<script>
function chh()
{
    for (var i = 0; i < document.getElementsByTagName("ul").length; i++)
    {
        document.getElementsByTagName("ul")[i].onmouseover = function()
        {
            for (var i = 0; i < document.getElementsByTagName("li").length; i++)
            {
                document.getElementsByTagName("li")[i].style.display = "block";
            }
        }
    }
}
</script>
</head>
<body onLoad="chh();">
<ul>
Friend Request Sent
<li style="display:none;">Cancel Request</li>
</ul>
<ul>
Friend Request Sent
<li style="display:none;">Cancel Request</li>
</ul>
<ul>
Friend Request Sent
<li style="display:none;">Cancel Request</li>
</ul>
</body>
</html>

Demo : http://jsfiddle.net/vZeP4/

You can do this with css, without using any javascript.

HTML

<ul>
    <li class="message">Friend Request Sent</li>
    <li class="cancel">Cancel Request</li>
</ul>
<ul>
    <li class="message">Friend Request Sent</li>
    <li class="cancel">Cancel Request</li>
</ul>
<ul>
    <li class="message">Friend Request Sent</li>
    <li class="cancel">Cancel Request</li>
</ul>

CSS

ul {
    margin-bottom: 20px;
}

ul > .cancel {
    display: none;
}
ul:hover > .cancel {
    display: block;
}

Demo

Also, notice that I have put Friend Request Sent within an li . This is because all children of a ul must be an li . Having anything else in there is invalid html.

Your second loop goes through all the <li> s and sets their display to block . You need to pick the <li> that is inside the <ul> hovered upon.

A quick fix would be:

function chh()
{
    for (var i = 0; i < document.getElementsByTagName("ul").length; i++)
    {
        document.getElementsByTagName("ul")[i].onmouseover = function()
        {
            this.childNodes[1].style.display = "block";         
        }
    }
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM