5

我在 for 循环中有这个 Javascript:

renderAElements[i] = document.createElement ("a");
        renderAElements[i].setAttribute("href", "#");
        renderAElements[i].setAttribute("class", "expander");
        renderAElements[i].appendChild(expand);

        alert (renderAElements[i].nodeValue);

其中 expand 被创建为:

var expand = document.createTextNode("+");

用于返回每个已创建元素的链接文本的警报返回 null。为什么是这样?

4

4 回答 4

5

因为您正在尝试获取nodeValueElement 节点而不是 Text 节点。

alert (renderAElements[i].firstChild.nodeValue);
于 2011-07-01T10:48:18.947 回答
1

这是因为 a 元素包含另一个元素而不是值。如果您想从节点中获取文本,您需要执行以下任一操作

renderAElements.childNodes[0].nodeValue

或者

renderAElements.innerText
于 2011-07-01T10:51:05.427 回答
0

看一下这个

<head>
    <script type="text/javascript">
        function GetTextNode () {
            var textContainer = document.getElementById ("textContainer");
            var textNode = textContainer.firstChild;
            alert (textNode.data);
        }
    </script> 
</head>
<body>
    <div id="textContainer">This is a simple text in the container.</div>
    <button onclick="GetTextNode ()">Get the contents of the container</button>
</body>
于 2011-07-01T10:49:47.620 回答
0

试试这个alert (renderAElements[i].firstChild.nodeValue);

于 2011-07-01T10:53:46.453 回答