我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?
HTML:
<meta property="video" content="http://video.com/video33353.mp4" />
当前回答
使用元根,然后获取和设置它的任何属性:
let meta = document.getElementsByTagName('meta')
console.log(meta.video.content)
> "http://video.com/video33353.mp4"
meta.video.content = "https://www.example.com/newlink"
其他回答
如果元标签是:
<meta name="url" content="www.google.com" />
JQuery将是:
const url = $('meta[name="url"]').attr('content'); // url = 'www.google.com'
JavaScript将是:(它将返回整个HTML)
const metaHtml = document.getElementsByTagName('meta').url // metaHtml = '<meta name="url" content="www.google.com" />'
function getMetaContentByName(name,content){
var content = (content==null)?'content':content;
return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}
以这种方式使用:
getMetaContentByName("video");
本页上的例子:
getMetaContentByName("twitter:domain");
如果您对获得所有元标记的更深远的解决方案感兴趣,可以使用这段代码
function getAllMetas() {
var metas = document.getElementsByTagName('meta');
var summary = [];
Array.from(metas)
.forEach((meta) => {
var tempsum = {};
var attributes = meta.getAttributeNames();
attributes.forEach(function(attribute) {
tempsum[attribute] = meta.getAttribute(attribute);
});
summary.push(tempsum);
});
return summary;
}
// usage
console.log(getAllMetas());
在Jquery中,你可以实现这一点:
$("meta[property='video']");
在JavaScript中,你可以通过以下方法实现:
document.getElementsByTagName('meta').item(property='video');
我个人更喜欢把它们放在一个对象哈希中,这样我就可以在任何地方访问它们。这可以很容易地设置为一个可注入的变量,然后所有东西都可以有它,它只抓取一次。
通过对函数进行包装,这也可以作为一行代码来完成。
var meta = (function () {
var m = document.querySelectorAll("meta"), r = {};
for (var i = 0; i < m.length; i += 1) {
r[m[i].getAttribute("name")] = m[i].getAttribute("content")
}
return r;
})();