简体   繁体   中英

How to load a html page and run a function in it with only one click?

I'm a beginner with HTML-CSS-JS and I have this problem :

When I'm at page1.html of my website, I can sort the different article of the page by selecting a sub-menu of my navigation bar (for example sub-menu 1 is "sport" and when I click on it only the article tagged as "sport" are visible). Here is the function :

        <script style="text/javascript">
    <!--
        function sortNews(id){
            var elmt = document.getElementsByTagName("section");

            for(var i = 0; i<elmt.length; i++){
                if(id == "all")
                    elmt[i].style.display = "block";
                else if(elmt[i].className != id)
                    elmt[i].style.display = "none";
                else
                    elmt[i].style.display = "block";
            }
        }
    // -->
    </script>

When I am at page2.html I can also select the submenu of page 1 via the navigation bar (it means when my mouse go over the menu "news" the sub-menu appear and I can click directly on "Sport"). My question is : can I load the page1.html AND run the function above without another click of the user ? (So the page of news with only the "sport" article will be loaded)

Thank you in advance ! Best regards

Call your function in body's onload attribute of your page1.html

<body onload="sortNews(id);">

But you will need something to get the id value.
You could use php and more specifically $_GET to do so.

(In your page2.html the link will be like :

<a href="page1.php?id=sport>Sports News !</a>

and in page1.php

<body onload="sortNews(<?php echo $_GET['id']; ?>);">

)

I'm not exactly sure what your asking, do you want a function to run when you load the page? If so: http://javascript.about.com/library/blonload.htm

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