0

JavaScript のテキスト ノードのプロパティについて少し混乱しています。次の html があるとします。

<html lang="en-US">
<head>
    <title>JavaScript test</title>
    <script type="text/javascript" src="test.js"></script>
</head>
<body onload="load()">
    <div>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
    </div>
    <ul>
        <li>1.</li>
        <li>2.</li>
    </ul>
</body>

そしてonload()機能:

function load()
{
    var bodyChildren = document.childNodes[0].childNodes;
    for(var i = 0; i < bodyChildren.length; i++) 
    {
        alert(bodyChildren[i].nodeType
            + ": " + bodyChildren[i].nodeName
            + ": " + bodyChildren[i].nodeValue);
    }
}

このhttp://www.w3schools.com/js/js_htmldom_navigation.aspは、「テキストノードの nodeValue はテキスト自体です」と伝え ていますが、次の出力が得られます。

3: #text: 
1: DIV: null
3: #text: 
1: UL: null
3: #text: 

nodeValueが返さnullelement node、 が「何もない」理由を説明できますtext nodeか?

編集: 空白については、ここでうまく説明されています: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM

4

2 に答える 2

3

それが仕様nodeValueに従って行うことであり、これを返します

Comment               - content of the comment
Document              - null
DocumentFragment      - null
DocumentType          - null
Element               - null
NamedNodeMap          - null
EntityReference       - null
Notation              - null
ProcessingInstruction - entire content excluding the target
Text                  - content of the text node

コメント、textNodes、および処理命令以外はすべて返されることに注意してください。他のすべてのノード タイプnull明示的に返されます。null

要素ノードのテキスト コンテンツを取得するにはtextContent(innerText古い IE の場合) を使用し、要素ノードの HTML を取得するには、innerHTML

于 2015-03-24T22:17:17.780 に答える
2

null要素ノードに対してnodeValue が返される理由

要素ノードには値がないためです。それらは基本的に名前、属性、および子のみを持ちます。

…そして、テキストノードには「何も」ありませんか?

それはあなたに何かを返します:それらの要素ノード間の空白。

于 2015-03-24T22:17:31.287 に答える