【问题标题】:Use hasAttribute in DomParser在 DomParser 中使用 hasAttribute
【发布时间】:2019-11-15 10:35:02
【问题描述】:

我在我的 Nodejs 脚本中使用函数 hasAttribute 来检查它是否存在。

var DOMParser = require('xmldom').DOMParser;

            var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);
            var allok = false;
            var x = xmlDoc.getElementsByTagName("TCafe");
            if (x.length != 0)
            {
               //Existiert Attribute prüfen
                if(x.hasAttribute('initvalue') == true){
                    if(x.getAttribute('initvalue') == '1'){
                        if(x.hasAttribute('type') == true){
                            if(x.getAttribute('type') == 'int'){
                                allok = true;
                            }
                        }
                    }
                }
            }

但是 node 一直告诉我 hasAttribute 不是一个函数。我对此消息感到困惑,因为在所有文档和参考资料中都可以使用此功能。我错过了什么吗? 替代方法?

【问题讨论】:

  • 您正在从“getElementsByTagName”获取一个集合。您应该尝试使用 x[0].hasAttribute("initvalue")。

标签: javascript node.js xml domparser


【解决方案1】:

getElementsByTagName() 返回具有给定标签名称的元素的实时 HTMLCollection,您必须使用特定的索引。由于hasAttribute() 返回布尔值,您可以缩短条件:

if(x[0].hasAttribute('initvalue')){......

if(x[0].getAttribute('initvalue') == '1'){.......

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2019-06-27
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多