简体   繁体   中英

How do I execute a jQuery function on page load if and only if the page is accessed via a specific hyperlink?

I have a simple link, like so:

<a href="page2.html">Go to Page 2</a>

I'd like that, when clicking this Button, it would go to the page and run a jQuery function, like so:

$("#object-selector div").hover(
    function () {
        $(this).animate({borderTopColor: '#fdcc06', borderRightColor: '#fdcc06', borderBottomColor: '#fdcc06', borderLeftColor: '#fdcc06'}, 200).children().animate({backgroundColor: '#fed944', color: '#351e00'}, 200);
    }, 
    function () {
        $(this).animate({borderTopColor: '#FFF', borderRightColor: '#FFF', borderBottomColor: '#FFF', borderLeftColor: '#FFF'}, 200).children().animate({backgroundColor: '#af081f', color: '#FFF'}, 200);
    }
);

But that function shouldn't execute if the Page is navigated to without clicking the link. Is there a way to do it?

If you want to do it all client-side, you could append a hash to your URL

<a href="page2.html#hover">Go to Page 2</a>

And then use the following code

<script>
if(window.location.hash === '#hover') {
    $(function() {
        $("#object-selector div").hover( ... , ... );
    });
}
</script>

Perhaps there is a way of achieving this with PHP. By changing your href into this

<a href="page2.html?click=1">Go to Page 2</a>

and then including the following on your page:

<?php
if ($_GET['click']){

echo "<script type=\"text/javascript\">";
echo "
$(\"#object-selector div\").hover(
    function () {
        $(this).animate({borderTopColor: '#fdcc06', borderRightColor: '#fdcc06', borderBottomColor: '#fdcc06', borderLeftColor: '#fdcc06'}, 200).children().animate({backgroundColor: '#fed944', color: '#351e00'}, 200);
    }, 
    function () {
        $(this).animate({borderTopColor: '#FFF', borderRightColor: '#FFF', borderBottomColor: '#FFF', borderLeftColor: '#FFF'}, 200).children().animate({backgroundColor: '#af081f', color: '#FFF'}, 200);
    }
);
";
echo "</script>";
}
?>

Note that this will only work on a server with PHP installed, not on your local machine.

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