简体   繁体   中英

Click on button after page reload

I have some links on the page and when user click on link, page is reloaded.

All links have some ID and all have the one same class.

I need to click on some other link after page is reloaded, but only if user click on some of the link with particular class (not anywhere, like menu link).

How I can do something like this using JS or jQuery?

It sounds like you are attempting to build a single page application, ie the application is mostly run by JavaScript instead of server side rendering. In this case page reloads are you enemy. A page reload is basically a restart of your page, and while you can keep state using cookies or localStorage , this will provide you with a rather poor user experience.

In this case, you would just add event handlers to any actions your user would take, and simply handle them in javascript without reloading the page from the server. If you need to get more data in response to the user's actions, you can use AJAX to pull that data from the server.

If you have to use links with urls (still unclear to me why that would be necessary), I would recommend using hash urls like so '#some-action' which will not reload the page when clicked. You can then attach an event handler to the link, or even listen for the url hash to change using the hashchange event. In this way you can know what link the user pressed.

If you are not trying to build a single page application, you will need to add code on the server to store the information you need in the page.

I did it.

So, I created function:

/**
 * Click on delivery link after page reload
 *
 * @return {boolean} [loacalStorage is available]
 */
$.fn.openDelivery = function(){
    if (localStorage) {
        var addedToCart = localStorage["addCart"];
        if (addedToCart) {
            setTimeout(function() {
                $('#showRight').trigger('click');
            }, 1500);
            localStorage.removeItem("addCart");
        }
        $(this).click(function(e) {
            localStorage["addCart"] = true;
        });

        return true;
    }

    return false;
};

And then called that function:

$(document).ready(function () {
    // Trigger delivery click
    $('.class-of-my-link').openDelivery();
});

In my case, page reloads after user add some item in shopping cart. With this function I click on link (with 1.5s delay) that opens cart of the user that is shown on the right side of the screen.

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