Checking URL fragment for a keyword

前端 未结 1 1334
忘掉有多难
忘掉有多难 2021-01-21 13:50

i use the following to take a URL e.g. domain.com/#2 and then i use that fragment to redirect the users to domain.com/?page=2.

However, sometimes the user may be shown j

1条回答
  •  心在旅途
    2021-01-21 14:51

    First set a global variable for the page number; then check if the "page" query string variable is set and is numeric (source).

    var pageNum = 0;
    
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    if(!isNaN(getParameterByName('page'))) pageNum += parseInt(getParameterByName('page'));
    

    Then check window.location.hash for the hash. If it is numeric, add it to pageNum. Else check if it is a command.

        if(!isNaN(parseInt(window.location.hash.replace(/#/, '')))) {
        pageNum += parseInt(window.location.hash.replace(/#/, ''));
    } else if(window.location.hash != null) {
        switch(window.location.hash) {
            case "feedback":
                window.location.href = 'domain.com/feedback';
                break;
            default: 
                // do nothing?
                break;
        }
    }
    

    Finally, redirect the user if pageNum > 0.

    if(pageNum > 0) window.location.href = 'domain.com/?page=' + pageNum;
    

    Complete code:

    var pageNum = 0;
    
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    
    if(!isNaN(getParameterByName('page'))) pageNum += parseInt(getParameterByName('page'));
    
    if(!isNaN(parseInt(window.location.hash.replace(/#/, '')))) {
        pageNum += parseInt(window.location.hash.replace(/#/, ''));
    } else if(window.location.hash != null) {
        switch(window.location.hash) {
            case "feedback":
                window.location.href = 'domain.com/feedback';
                break;
            default: 
                // do nothing?
                break;
        }
    }
    
    if(pageNum > 0) window.location.href = 'domain.com/?page=' + pageNum;
    

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