使用 javascript 将话题标签附加到 URL

问题描述 投票:0回答:6
javascript ajax
6个回答
48
投票

您可以更改

location.hash
属性,它将更改当前锚点标识符,而无需离开页面,例如您可以:

<a href="http://mysite.com/cats" id="cats" class="ajaxLink">Cats</a>
<a href="http://mysite.com/dogs" id="dogs" class="ajaxLink">Dogs</a>

然后:

$('.ajaxLink').click(function (e) {
  location.hash = this.id; // get the clicked link id
  e.preventDefault(); // cancel navigation

  // get content with Ajax...
});​

16
投票

如果哈希值具有以下形式的感叹号,Google 将会索引该哈希值:

#!dogs

然后假设这些是面向 AJAX 的:


0
投票

出于安全原因,您无法在不重新加载 javascript 页面的情况下设置 window.location.href。

据我所知,有些人说 Google 会索引 # 个网址,但它们不会被视为单独的页面,我认为这不是您想要的。我对 SEO 的经验也很少。


0
投票

虽然简单是最好的,但如果您只想自动化此过程或使其通用,那么您可以使用这个精简版插件jquery.hashTag.js

$('a').hashTag({
    source: function() {
      return $(this).attr('id');
    }
  });

只需将此片段放入 $(document).ready 中即可。

它将自行完成剩下的工作。 就像自动点击 id 作为哈希值提供的链接一样。


0
投票
window.location.hash = 'yourhash'

-1
投票

BenMills,没有人提到location.href,它是关于location.hash,不需要重新加载页面。

© www.soinside.com 2019 - 2024. All rights reserved.