通过选择`property`属性获取`Meta`属性`content`
在jQuery中你可以这样做:
$("meta[property='fb:app_id']").attr("content");
这将使用property
属性“fb:app_id”的meta
-tag为您提供content
属性值。
我怎么能用普通的’Javascript?
先感谢您。 🙂
肯尼斯
不像JQuery那么优雅我害怕……
var metaTags=document.getElementsByTagName("meta"); var fbAppIdContent = ""; for (var i = 0; i < metaTags.length; i++) { if (metaTags[i].getAttribute("property") == "fb:app_id") { fbAppIdContent = metaTags[i].getAttribute("content"); break; } } console.log(fbAppIdContent);
document.querySelector('meta[property~="fb:app_id"][content]').content
注意:有些使用property
属性:
而其他人使用name
属性:
我使用以下方法从两个变体中获取值:
var appId = (function(c) { for (var a = document.getElementsByTagName("meta"), b = 0;b < a.length;b++) { if (c == a[b].name || c == a[b].getAttribute("property")) { return a[b].content; } } return false; })("fb:app_id"); console.log(appId); //(bool)false if meta tag "fb:app_id" not exists.
同样可以用于每个其他元标记 - 只需更改闭包函数的输入值(例如,从fb:app_id
到description
)。
编辑:或者作为更通用的function:
function getContentByMetaTagName(c) { for (var b = document.getElementsByTagName("meta"), a = 0; a < b.length; a++) { if (c == b[a].name || c == b[a].getAttribute("property")) { return b[a].content; } } return false; } console.log(getContentByMetaTagName("og:title"));