是否可以使用jQuery来读取元标记

Ank*_*kur 152 jquery dom meta-tags

是否可以使用jQuery来读取元标记.如果是这样,您知道代码的基本结构是什么,或者链接到任何教程.

Mif*_*Fox 290

只需使用以下内容:

var author = $('meta[name=author]').attr("content");
Run Code Online (Sandbox Code Playgroud)

  • var author = $("meta [name ='author']").attr("content"); 引用只是一点点. (2认同)

Dan*_*ret 19

这个解析器会帮助你吗?

https://github.com/fiann/jquery.ogp

它将元OG数据解析为JSon,因此您可以直接使用数据.如果您愿意,您可以使用JQuery直接读/写它们.例如:

$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());
Run Code Online (Sandbox Code Playgroud)

注意属性值周围的单引号; 这可以防止jQuery中的解析错误.

这是我在这里给出的回复:https://stackoverflow.com/questions/4059207

  • 你在这里指定的解析器(以及一些其他问题)是针对OG DATA(你甚至自己这么说),而OP则询问META TAGS而不是OG数据. (3认同)

cha*_*ons 8

我刚试过这个,这可能是一个特定于jQuery版本的错误,但是

$("meta[property=twitter:image]").attr("content");
Run Code Online (Sandbox Code Playgroud)

导致以下语法错误:

Error: Syntax error, unrecognized expression: meta[property=twitter:image]
Run Code Online (Sandbox Code Playgroud)

显然它不喜欢冒号.我能够通过使用这样的双引号和单引号来修复它:

$("meta[property='twitter:image']").attr("content");
Run Code Online (Sandbox Code Playgroud)

(jQuery版本1.8.3 - 抱歉,我本来对@Danilo发表评论,但它不会让我发表评论)


Sau*_*uce 5

jQuery现在支持.data();,所以如果你有

<div id='author' data-content='stuff!'>
Run Code Online (Sandbox Code Playgroud)

使用

var author = $('#author').data("content"); // author = 'stuff!'
Run Code Online (Sandbox Code Playgroud)