JavaScript中的属性值

时间:2018-12-13 17:47:33

标签: javascript dom

我正在使用以下代码创建图像标签。

var a = new DOMParser().parseFromString('<img src="/hello" alt="Promised">', "text/xml");
for(var b in a){
    alert('b is: ' + b + '.Value is: ' + a[b]);
}

在上面的代码中,我无法获取图像的alt属性的值。为什么alt不会在for循环中显示?

我知道我们可以将属性获取为:

var a = document.getELementsByTagName('img')[0].alt; 

但是为什么它在for循环中不起作用?

1 个答案:

答案 0 :(得分:1)

将其解析为XML并没有帮助,但它不是有效的XML(没有结束标记)。试试这个:

new XMLSerializer().serializeToString(a)

您收到此解析器错误:

<img src="/hello" alt="Promised">
    <parsererror xmlns="http://www.w3.org/1999/xhtml" style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
        <h3>This page contains the following errors:</h3>
        <div style="font-family:monospace;font-size:12px">error on line 1 at column 34: Extra content at the end of the document
        </div>
        <h3>Below is a rendering of the page up to the first error.</h3>
    </parsererror>
</img>

如果您修复XML(结束标记)并重复,您将得到:

var a = new DOMParser().parseFromString('<img src="/hello" alt="Promised"></img>', "text/xml");
new XMLSerializer().serializeToString(a)

结果:

<img src="/hello" alt="Promised"/>

如果您将其解析为HTML:

var a = new DOMParser().parseFromString('<img src="/hello" alt="Promised">', "text/html");

您将得到此信息:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head></head>
    <body>
        <img src="/hello" alt="Promised" />
    </body>
</html>

要遍历元素的属性,您需要修复循环:

var elem = a.getElementsByTagName('img')[0];
for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    if (attrib.specified) {
        console.log('b is: ' + attrib.name + '.  Value is: ' + attrib.value);
    }
}