JavaScript - 提取文档元字段的最快方法
我需要提取文档的“描述”元标记。
默认方法是使用 document.getElementsByTagName('META') ,然后迭代数组 - 如: http://www.rgagnon.com/jsdetails/js-0070.html
但我想知道是否没有其他更快的“一行代码”方法。 我不熟悉 xPath - 但也许这可行? 有任何想法吗?
I need to extract the document's "description" meta tag.
The default way would be to use document.getElementsByTagName('META') and then iterate through the array - as found in: http://www.rgagnon.com/jsdetails/js-0070.html
But I'm wondering if there's no other quicker, "one line of code" approach. I'm not familiar with xPath - but maybe that could work? Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然...
这假设有一个名为“描述”的元标记。
为了更完整,无论大小写,这都会捕获描述。
sure...
This presumes that there is a Meta Tag named description of course.
To be more complete, this would catch the description regardless of case.
您可以使用 XPath 来完成此操作(在支持
document.evaluate
的客户端中),但这可能有点过头了:You can do it with XPath (in clients supporting
document.evaluate
) but that would probably be an overkill:Scunliffe,我认为你的建议肯定会成功,至少多行函数会。
我想出了一个不能在 Webkit(Chrome + Safari)上运行但非常紧凑的解决方案:
这将利用 NodeList 对象上的 nameItem() 函数,寻找其他程序员编写“描述”的最可能的方式。 请注意,这将检索标签属性的值,同时忽略属性名称的大小写:
但是唉(Oy Vey)nameItem() 不适用于 Safari 和 Safari。 Chrome :-( 也许这些浏览器有另一种方法......
Scunliffe, I think your suggestion will definitely do the trick, at least the multi-line function will.
I came up with a solution that doesn't run on Webkit (Chrome + Safari) but which is very compact:
This will utilize the namedItem() function over the NodeList object, looking for most likely ways another programmer might write "description". Note that this will retrieve the values of tag's attribute, while ignoring case for attribute names:
But alas (Oy Vey) the nameItem() doesn't work on Safari & Chrome :-( Maybe there's an alternative approach for those browsers...
它还取决于您所说的“最快”是什么意思 - 您是指您可以编写的最短代码,还是浏览器的最快响应?
为了获得最快的响应,只需查看 head 元素中的元元素,然后选择任何名称为“description”的元素。
It also depends on what you mean by 'quickest'- do you mean the shortest code you can write, or the fastest response from the browser?
For the quickest response, just look at the meta elements in the head element, and pick out any with the name 'description'.