XML DOM data 属性

  • 定义和使用

    data 属性设置或返回注释文本。
  • 浏览器支持

    Internet Explorer Chrome FireFox Safari Opera
    9.0(包含)以上支持 4.0(包含)以上支持 2.0(包含)以上支持 3.0(包含)以上支持 9.0(包含)以上支持
    所有主流的浏览器均支持 data 属性。
  • 语法

    commentNode.data
  • 示例

    以下代码片段将 "books_comment.xml" 加载到 xmlDoc 中,并从第一个<book>元素输出注释文本:
    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            myFunction(xhttp);
        }
    };
    xhttp.open("GET", "books_comment.xml", true);
    xhttp.send();
    
    function myFunction(xml) {
        var x, i, txt, xmlDoc;
        txt = "";
        xmlDoc = xml.responseXML;
        x = xmlDoc.getElementsByTagName("book")[0].childNodes;
        for (i = 0; i < x.length; i++) { 
            // Process only comment nodes
            if (x[i].nodeType == 8) {
                txt += x[i].data + "<br>";
            }
        }
        document.getElementById("demo").innerHTML = txt; 
    }
    </script>
    
    </body>
    </html>
    
    尝试一下
    在上面的示例中,我们使用循环和 if-test 来确保仅处理注释节点。 注释节点的节点类型为8。