How can I execute a script after calling [removed].href?

前端 未结 8 1416
执笔经年
执笔经年 2020-12-03 10:48

I have a script that redirects the user to another page. I want to load some content into a div on the new page after the new page has fully loaded. How can I do this. The f

相关标签:
8条回答
  • 2020-12-03 11:04

    An easy way to pass data to your page you are redirecting to would be to set some url parameters.

    For example:

    window.location.href - "http://youpage.com/?key=value"
    

    When that page loads you could have a:

    $(document).ready(function(){
    
        var my_param = getUrlParameter('key');
        if(my_param == "value"){
    //do your stuff here
    }
    
    });
    
    
    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;
    
        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');
    
            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    };
    
    0 讨论(0)
  • 2020-12-03 11:16

    You can do this a few different ways. Try leveraging the localstorage API and passing info or content with a name and value pair (or a few of them) and unpack it on the receiving end.

    On the page you're redirecting to, check for the localstorage key, and then load the contents of it (the aforementioned name and value pairs) into a div.

    As an alternative, you can write one script file that you can deploy to several pages; do a check on window.location.href and conditionally load script accordingly. If you're on the redirected page, you can run whatever script you like. The nice part about doing it this way is that you're still working with one JS file - no need to fragment your code (assuming, of course, that the pages you're working with are all on the same site).

    You don't need to do anything with php if you don't want to, or hashes... there's a few nifty tools that will do the trick if you can leverage HTML5 and its associated APIs.

    0 讨论(0)
提交回复
热议问题