【问题标题】:JS get value of generated textnodeJS获取生成的textnode的值
【发布时间】:2011-09-26 16:15:20
【问题描述】:

我在 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。这是为什么呢?

【问题讨论】:

标签: javascript textnode


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是因为 a 元素包含另一个元素而不是值。如果你想从节点中取出文本,你需要这样做

    renderAElements.childNodes[0].nodeValue
    

    renderAElements.innerText
    

    【讨论】:

      【解决方案3】:

      Check this out

      <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>
      

      【讨论】:

        【解决方案4】:

        因为您试图获取 Element 节点的 nodeValue 而不是 Text 节点。

        alert (renderAElements[i].firstChild.nodeValue);
        

        【讨论】:

        • 干杯。在您的答案出现的同时发现了问题。
        猜你喜欢
        • 2012-06-08
        • 2020-09-22
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-06
        • 1970-01-01
        • 2013-09-05
        相关资源
        最近更新 更多