代码之家  ›  专栏  ›  技术社区  ›  Tomas Andrle

Javascript从#锚定重定向到单独页面

  •  6
  • Tomas Andrle  · 技术社区  · 15 年前

    旧链接样式:

    /all_products#A
    /all_products#B
    /all_products#C
    

    /products/A
    /products/B
    /products/C
    

    是否可以使用Javascript自动从/all#u products#A重定向到/products/A?

    JQuery就可以了,反正它已经在网站上使用了。

    5 回复  |  直到 15 年前
        1
  •  12
  •   janpio WillBroadbent    6 年前

    我添加了这个新的答案,以包括这两方面的一些最佳实践 extracting the hash from the url doing a redirect .

    // Closure-wrapped for security.
    (function () {
        var anchorMap = {
            "A": "/products/A",
            "B": "/products/B",
            "C": "/products/C"
        }
        /*
        * Best practice for extracting hashes:
        * https://stackoverflow.com/a/10076097/151365
        */
        var hash = window.location.hash.substring(1);
        if (hash) {
            /*
            * Best practice for javascript redirects: 
            * https://stackoverflow.com/a/506004/151365
            */
            window.location.replace(anchorMap[hash]);
        }
    })();
    
        2
  •  3
  •   James Wheare    15 年前

    将其放在HTML的顶部 <head> 尽可能使其在下载其余页面资源之前执行:

    <script>
    function checkURL() {
        var old_path = '/all_products';
        if (window.location.pathname != old_path) {
            // Not on an old-style URL
            return false;
        }
        // Some browsers include the hash character in the anchor, strip it out
        var product = window.location.hash.replace(/^#(.*)/, '$1');
        // Redirect to the new-style URL
        var new_path = '/products';
        window.location = new_path + '/' + product;
    }
    checkURL();
    </script>
    

    这将检查当前页面URL,并重定向它是否与旧式路径匹配。

    window.location 对象,该对象包含当前URL的所有部分,这些部分已拆分为多个组件。

        3
  •  2
  •   Gregory    15 年前

    var urlSplit = document.URL.split("#");
    if (urlSplit[1]) {
        location.href = "http://www.example.org" + "/" + urlSplit[1];
    }
    else {
        location.href = "http://www.example.org";
    }
    
        4
  •  0
  •   kkyy    15 年前

    使用jquery,只需将href替换为正确的href即可:

    $('a').each(function() {
      this.href = this.href.replace(/all_products#/, 'products/');
    });
    

    或捕获单击并重定向:

    $('a').click(function() {
      window.location = this.href.replace(/all_products#/, 'products/');
      return false;
    });
    
        5
  •  -1
  •   TheVillageIdiot    15 年前

    <a href="/all_products#A" onclick="return redirectMe(this);">A</a>
    <a href="/all_products#B" onclick="return redirectMe(this);">B</a>
    <a href="/all_products#C" onclick="return redirectMe(this);">C</a>
    <a href="/all_products#D" onclick="return redirectMe(this);">D</a>
    <a href="/all_products#E" onclick="return redirectMe(this);">E</a>
    
    <script type="text/javascript">
    function redirectMe(a){
       var aa=a+"";
       window.location=aa.replace(/#/g,"/");
    }
    </script>