6

我有一组链接,其中#anchors 指向一个网页,我想顺利移动到一个模型,每个链接都有一个单独的网页。我希望旧链接使用重定向继续工作。

旧链接样式:

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

新链接样式:

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

我知道服务器没有收到请求中的#anchor 名称,但 Javascript 可能。

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

JQuery 会很好,无论如何它都在网站上使用。

4

5 回答 5

12

我添加了这个新答案以包含一些从 url 中提取哈希执行重定向的最佳实践。

// 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]);
    }
})();
于 2014-01-17T23:53:41.147 回答
3

尽可能将其放在 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 的所有部分的对象。

让这个脚本更通用留给实现者作为练习。

于 2009-08-24T06:51:26.897 回答
2

我希望这可以帮助:)

var urlSplit = document.URL.split("#");
if (urlSplit[1]) {
    location.href = "http://www.example.org" + "/" + urlSplit[1];
}
else {
    location.href = "http://www.example.org";
}
于 2009-08-24T06:07:59.777 回答
0

使用 jquery,只需将 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;
});
于 2009-08-20T10:41:49.950 回答
-1

这可能会有所帮助:

<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>   
于 2009-08-20T10:39:24.497 回答