我正在尝试使用JavaScript从html页面中读取元数据。我创建了一个包含所有meta标签的数组,并尝试读取属性字段,但似乎无法使其正常工作。这里是控制台:
>meta[6]
<meta property="og:image" content="http://www. example.com/img/1.png">
>meta[6].property
undefined
>meta[6].content
"http://www. example.com/img/1.png"如何才能访问内容而不能访问属性字段?如何获取属性?
发布于 2011-05-24 11:33:05
您需要getAttribute函数:
>meta[6].getAttribute('property');
"og:image"发布于 2011-05-24 13:12:51
要回答这个问题:
“如何才能访问内容而不访问属性字段”
内容是HTML meta element的标准属性,因此浏览器将为相关的DOM元元素创建一个等效的DOM属性。
属性不是HTML meta element的标准属性,所以一些浏览器不会创建类似的属性(例如火狐),而其他浏览器(例如IE)会创建类似的属性。因此,应用于任何非标准属性值,但直接DOM属性访问应用于标准属性值。
一般来说,您不应该在HTML元素上使用非标准属性,那么您始终可以使用DOM属性访问值(这是最适合HTML DOM元素的方法)。
请注意,HTML5 meta element与上面链接的HTML4.01元素相同,但是HTML4规范可能是目前在一般web上使用的更好的规范。只有在针对特定浏览器的HTML5特性时,才应该使用特定于html5的代码。
发布于 2011-10-20 07:51:17
下面是一个完整的工作示例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Cross-Window HTML</title>
<meta property="og:title" content="Share Title" />
<meta property="og:description" content="Share Page Description" />
<meta property="og:image" content="Path to Share Image" />
<link rel="canonical" href="http://127.0.0.1/newWindowWrite.html" />
<script type="text/javascript">
function GetMetaValue(meta_name) {
var my_arr = document.getElementsByTagName("meta");
for (var counter = 0; counter < my_arr.length; counter++) {
console.log(my_arr[counter].getAttribute('property'));
if (my_arr[counter].getAttribute('property') == meta_name) {
return my_arr[counter].content;
}
}
return "N/A";
}
function newHTML() {
HTMLstring = '<html>\n';
HTMLstring += '<head>\n';
HTMLstring += '<title>Google +1</title>\n';
HTMLstring += '<meta property="og:title" content="' + GetMetaValue('og:title') + '"/>\n';
HTMLstring += '<meta property="og:description" content="' + GetMetaValue('og:description') + '"/>\n';
HTMLstring += '<meta property="og:image" content="' + GetMetaValue('og:image') + '"/>\n';
HTMLstring += '<link rel="canonical" href="' + location.href + '"/>\n';
HTMLstring += '</head>\n';
HTMLstring += '<body>\n';
HTMLstring += '<div id="shareContent">\n';
HTMLstring += '</div>\n';
HTMLstring += '</body>\n';
HTMLstring += '</html>';
console.log(HTMLstring);
newwindow = window.open();
newdocument = newwindow.document;
newdocument.write(HTMLstring);
newdocument.close();
}
</script>
</head>
<body>
<div onclick="newHTML();">Spawn Sharing Window</div>
</body>
</html>https://stackoverflow.com/questions/6105335
复制相似问题