【问题标题】:How do I retrieve the content of meta property og in JavaScript?如何在 JavaScript 中检索元属性 og 的内容?
【发布时间】:2017-02-18 04:23:58
【问题描述】:

我在 HTML 代码中有以下内容:

<meta name="citation_journal_title" content="Psychological Bulletin" />

使用以下方法很容易获取内容:

document.getElementsByName("citation_journal_title")[0].getAttribute("content")

但是,我无法处理:

<meta property="og:site_name" content="APA PsycNET" />

如何检索og:site_name 的内容? 我知道 How do I get the information from a meta tag with javascript? 的问题,但我正在寻找一些非常简单的东西,比如

document.getElementsByName("citation_journal_title")[0].getAttribute("content")

【问题讨论】:

标签: javascript jquery html attributes selector


【解决方案1】:

您需要使用属性选择器[attr=value] 来完成这项工作。像这样在querySelector() 中使用它

var attr = document.querySelector("meta[property='og:site_name']").getAttribute("content");
console.log(attr);
&lt;meta property="og:site_name" content="APA PsycNET" /&gt;

【讨论】:

  • 就是这样!谢谢。
【解决方案2】:

Jquery中,可以使用attr()

$('meta[property="og:site_name"]').attr('content')

JavaScript中,你可以使用querySelector

所有现代浏览器都支持querySelector,也支持IE8。

var element = document.querySelector('meta[property="og:site_name"]');
var content = element && element.getAttribute("content");
console.log(content);

参考文献

console.log($('meta[property="og:site_name"]').attr('content'));

var element = document.querySelector('meta[property="og:site_name"]');
var content = element && element.getAttribute("content");
console.log(content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta property="og:site_name" content="APA PsycNET" />

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2012-05-22
    • 2011-11-25
    • 2023-03-10
    • 2021-02-27
    • 2011-08-03
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多