简体   繁体   中英

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> 
            </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>

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