使用 javascript 将主题标签附加到 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2366481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attaching hashtag to URL with javascript
提问by alooficha
I want to build an ajax site without sacrificing SEO. My question is: If I have link on my page like this:
我想在不牺牲 SEO 的情况下构建一个 ajax 站点。我的问题是:如果我的页面上有这样的链接:
<a href="http://example.com/cats" id="cats">Cats</a>
<a href="http://example.com/dogs" id="dogs">Dogs</a>
...when each link is clicked I would like to update the address bar with the corresponding hashtag. So, if "Cats" link is clicked the current location will be http://example.com/#catsand I can use this to show my ajax content. If javascript is off or user is search engine, they will go directly to /cats
...当每个链接被点击时,我想用相应的主题标签更新地址栏。因此,如果单击“Cats”链接,当前位置将是http://example.com/#cats,我可以使用它来显示我的 ajax 内容。如果javascript关闭或用户是搜索引擎,他们将直接转到/cats
回答by CMS
You can change the location.hashproperty, it will change the current anchor identifier without navigating away form the page, for example you could:
您可以更改该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>
Then:
然后:
$('.ajaxLink').click(function (e) {
location.hash = this.id; // get the clicked link id
e.preventDefault(); // cancel navigation
// get content with Ajax...
});?
回答by anon
Google will index a hash if it has an exclamation mark in the form: #!dogs
如果散列带有以下形式的感叹号,Google 会将其编入索引: #!dogs
It then assumes that these are AJAX-oriented:
然后假设这些是面向 AJAX 的:
回答by BenMills
You cannot set the window.location.href without reloading the page in javascript for security reasons.
出于安全原因,您不能在不重新加载 javascript 页面的情况下设置 window.location.href。
From what I've seen some people are saying Google will index # urls but they will be not considered separate pages and I think that is not what you want. I also have very little experience with SEO.
根据我所看到的,有些人说 Google 会将 # url 编入索引,但它们不会被视为单独的页面,我认为这不是您想要的。我对 SEO 的经验也很少。
回答by Arpit Singh
Although simplicity is best, but if you just want to automate this process or make it genericise then you can use this lite plugin jquery.hashTag.js
虽然简单是最好的,但如果你只是想自动化这个过程或使它通用化,那么你可以使用这个 lite 插件jquery.hashTag.js
$('a').hashTag({
source: function() {
return $(this).attr('id');
}
});
Just put this snippet inside $(document).ready.
只需将此代码段放在 $(document).ready 中即可。
It will do rest of the work itself. Like auto clicking on the link whose id was provided as the hash.
它会自己完成剩下的工作。就像自动点击其 id 作为哈希值提供的链接一样。
回答by ZurabWeb
BenMills, noone mentioned location.href, it's about location.hash which does not require page reload.
BenMills,没有人提到location.href,它是关于location.hash,不需要重新加载页面。

