您可以更改
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...
});
如果哈希值具有以下形式的感叹号,Google 将会索引该哈希值:
#!dogs
然后假设这些是面向 AJAX 的:
出于安全原因,您无法在不重新加载 javascript 页面的情况下设置 window.location.href。
据我所知,有些人说 Google 会索引 # 个网址,但它们不会被视为单独的页面,我认为这不是您想要的。我对 SEO 的经验也很少。
虽然简单是最好的,但如果您只想自动化此过程或使其通用,那么您可以使用这个精简版插件jquery.hashTag.js
$('a').hashTag({
source: function() {
return $(this).attr('id');
}
});
只需将此片段放入 $(document).ready 中即可。
它将自行完成剩下的工作。 就像自动点击 id 作为哈希值提供的链接一样。
window.location.hash = 'yourhash'
BenMills,没有人提到location.href,它是关于location.hash,不需要重新加载页面。