简体   繁体   中英

How can i make buttons on a HTML page show different information

i am making an information website for a school assignment, i want to have a button/s to make different information display on the page. how do i go about doing this in HTML or other applicable languages, Thanks

Use JavaScript!

<body>
    <input id="button1" type="button" value="click me">
    <input id="button2" type="button" value="click me, too">
    <p id="output"></p>

    <script>
        /* Get references to your elements. */
        var button1=document.getElementById("button1");
        var button2=document.getElementById("button2");
        var output=document.getElementById("output");

        /* Add click event listeners to your buttons so you can interact with them. */
        button1.addEventListener("click",clickButton1);
        button2.addEventListener("click",clickButton2);

        /* Write functions to handle displaying various content depending on which button you press. */
        function clickButton1(event_){
            output.innerHTML="You clicked button1!";
        }

        function clickButton2(event_){
            output.innerHTML="You clicked button2!";
        }
    </script>
</body>

Basically, your click event listeners handle what to display when a button is pressed. I'm just changing the text in ap element, but you could do a lot more than that. For example, store the different html you want to display in hidden divs and only display them when a button is pressed. Hope this helps!

I believe you could do this in CSS as well, the big thing to note in the example is that each <a> has the #(id of div) in the href attribute. Since I don't know the exact context for your predicament, I can't say this would work how you want it to, but I just really dislike using javascript if I don't have to.

 .container > div { display: none } .container > div:target { display: block; } ul.nav { list-style-type: none; } ul li { display: inline-block; width: 100px; } ul li button { border: 1px solid grey; border-radius: 2px; padding-left: 5px; box-sizing: padding-box; } 
 <ul class="nav"> <li> <button><a href="#firstTab">Tab 1</a> </button> </li> <li> <button><a href="#secondTab">Tab 2</a> </button> </li> <li> <button><a href="#thirdTab">Tab 3</a> </button> </li> <li> <button><a href="#fourthTab">Tab 4</a> </button> </li> <li> <button><a href="#fifthTab">Tab 5</a> </button> </li> </ul> <div class="container"> <div id="firstTab">Hello Tab 1</div> <div id="secondTab">Hello Tab 2</div> <div id="thirdTab">Hello Tab 3</div> <div id="fourthTab">Hello Tab 4</div> <div id="fifthTab">Hello Fifth Tab</div> </div> 

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