【问题标题】:Output is null, when getting the nodeValue获取nodeValue时输出为null
【发布时间】:2018-02-11 19:22:30
【问题描述】:

我在 javascript 中通过这段代码获取节点的值,

function show(){
        var x = document.getElementsByTagName("allowance")[0];
        var y = x.nodeValue;
        alert(y);
    }

来自 html 中的这个 xml。

<xml style="display: none">
        <students id="lul">
            <student>
                <name>Mark Fajardo</name>
                <allowance>9999</allowance>
            </student>
            <student>
                <name>Rencie Macale</name>
                <allowance>20</allowance>
            </student>
        </students>
    </xml>

但是警报项目的输出只是空的。帮助

【问题讨论】:

    标签: javascript html xml null nodevalue


    【解决方案1】:

    你也可以像这样使用innerHTML

    y = document.getElementsByTagName("allowance")[0].innerHTML;
    alert(y);
    

    【讨论】:

    • 谢谢!这就是我要找的。​​span>
    【解决方案2】:

    您应该使用 textContent 从 XML 标记中获取文本,因为 nodeValue 仅返回 XML 中 元素 上的 文本节点 的文本值> 节点,nodeValue 属性始终为null

    function show() {
      var x = document.getElementsByTagName("allowance")[0];
      var y = x.textContent;
      console.log(y);
    }
    
    show()
    <xml style="display: none">
      <students id="lul">
        <student>
          <name>Mark Fajardo</name>
          <allowance>9999</allowance>
        </student>
        <student>
          <name>Arabella Raymundo</name>
          <allowance>20</allowance>
        </student>
      </students>
    </xml>

    【讨论】:

    • 当然,innerHTML 并不是真正用于非 HTML 而是 XML 的正确方法,但它可能适用于大多数浏览器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2011-04-28
    • 2011-11-09
    • 2013-04-21
    • 2020-08-12
    • 2013-01-25
    • 2019-07-06
    相关资源
    最近更新 更多