开发者

Javascript click on a specific link and show div (no jQuery)

I have a list or items, and I want to add a class to a div once you click on a certain list item (ie in this example, the last list item).

Code sample below:

        <ul class="tier-1"> 
            <li class="first"> 
                 <a href="/">HOME</a> 
            </li> 
            <li>
                 <a href="">SECTIONS</a> 
   开发者_C百科         </li> 
            <li class="Login Nav Link last"> 
                 <a href="#login" class="Logi Nav **Link**">LOGIN</a> 
            </li> 
        </ul>
        <div class="nav-login"></div>

Click on 'LOGIN' link, and the div 'nav-login' should add class 'show'.

Note: I cannot change the mark-up.


Try this:

<li class="Login Nav Link last"> 
    <a href="#login" class="Login Nav Link" onclick="toggle()">LOGIN</a> 
</li>

<div id="nav-login"></div>

<script>
function toggle(){
    var div1 = document.getElementById('nav-login')
    if (div1.style.display == 'none') {
        div1.style.display = 'block'
    } else {
        div1.style.display = 'none'
    }
}
</script>

Note that for this method you need to change class="nav-login" into id="nav-login"


This should work with your markup. You should probably not rely on grabbing the last element, that is just to keep the answer short. You should check the element classname instead.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <script language="javascript" type="text/javascript">
        window.onload = function() {
            var links = document.getElementsByTagName("a");
            links[links.length-1].onclick = function () {
                var divs = document.getElementsByTagName("div");
                divs[divs.length-1].className += " show";
            }
        }
        </script>
    </head>
    <body>
        <ul class="tier-1">
            <li class="first">
                <a href="/">HOME</a>
            </li>
            <li>
                <a href="">SECTIONS</a>
            </li>
            <li class="Login Nav Link last">
                <a href="#login" class="Login Nav Link">LOGIN</a>
            </li>
        </ul>
        <div class="nav-login"></div>
    </body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜