javascript 设置描述元标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13095209/
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
Set description meta tag
提问by Alex Ritter
I have recently added the following line of Javascript code to a few pages on my site, in order to pull the title tag from the H1 element with the CSS class of "Category-H1".
我最近在我网站上的几个页面中添加了以下 Javascript 代码行,以便从具有“Category-H1”CSS 类的 H1 元素中提取标题标签。
document.title = document.getElementsByClassName("Category-H1")[0].innerHTML;
I am curious, can I do something similar to pull in the description tag using JS from my H2 element?
我很好奇,我可以做一些类似于从我的 H2 元素中使用 JS 拉入描述标签的事情吗?
回答by D. Strout
This is doable, but I'm not sure if it would accomplish what you're hoping for. Most people use meta description tags for SEO purposes, but many (most?) search engines won't recognize the description if it is set by JavaScript after the page loads*. Still, if you want to do this:
这是可行的,但我不确定它是否会实现您的期望。大多数人将元描述标签用于 SEO 目的,但如果在页面加载后由 JavaScript 设置,许多(大多数?)搜索引擎将无法识别该描述*。不过,如果你想这样做:
var meta=document.getElementsByTagName("meta");
for (var i=0; i<meta.length; i++) {
if (meta[i].name.toLowerCase()=="description") {
meta[i].content=document.getElementsByClassName("Category-H1")[0].innerHTML;
}
}
Hope this helps!
希望这可以帮助!
*坦率地说,我不说话 experience在这里体验,只是常识。元信息是动态的真的没有意义,所以即使蜘蛛足够聪明可以运行JavaScript,为什么它会在这样做之后重新检查元信息?
回答by Elliot Bonneville
You can use the getAttribute()
function to do this:
您可以使用该getAttribute()
函数来执行此操作:
document.title = document.getElementsByClassName("Category-H1")[0].getAttribute("yourDescriptionMetaTag");
回答by Chris Miller
I don't think this is going to be good for SEO. While it may work, I don't think spiders are expecting these tags to be dynamic. But if SEO isn't the point, here's another answer that shows how with jquery.
我不认为这对 SEO 有好处。虽然它可能有效,但我不认为蜘蛛希望这些标签是动态的。但如果 SEO 不是重点,这里有另一个答案,显示了如何使用 jquery。