javascript jquery无法读取未定义的属性“getAttribute”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29087084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:04:51  来源:igfitidea点击:

jquery Cannot read property 'getAttribute' of undefined

javascriptjquerysoapexchangewebservices

提问by zoomynn

The javascript I'm using works completely fine in firefox and ie but has this error when run on chrome and safari. I'm not entirely sure why it's failing.

我使用的 javascript 在 firefox 和 ie 中完全正常,但在 chrome 和 safari 上运行时出现此错误。我不完全确定它为什么失败。

        var response = asyncResult.value;
        if (window.DOMParser) {
            var parser = new DOMParser();
            xmlDoc = parser.parseFromString(response, "text/xml");

        }
        else 
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(response);
        }

        console.log(xmlDoc);
         var changeKey = xmlDoc.getElementsById("t:ItemId")[0].getAttribute("ChangeKey");

The console shows this message but outputs the xmlDoc just fine when I have it set to console.log()

控制台显示此消息,但当我将其设置为 console.log() 时输出 xmlDoc 就好了



Uncaught TypeError: Cannot read property 'getAttribute' of undefined        r.js 
soapToGetItemDataCallback    r.js
r.onreadystatechange    outlookwebapp-15.js:21 
$h.EwsRequest.x_1    outlookwebapp-15.js:21 
(anonymous function)   outlookwebapp-15.js:21

回答by Wilfredo P

The problem is that you are trying to get the element by ID and using [0], I guess you wanna getElementsByTagNamebecause that the result is undefined, the code should be:

问题是您正在尝试通过 ID 获取元素并使用[0],我猜您想要getElementsByTagName因为结果未定义,代码应该是:

var changeKey = xmlDoc.getElementsById("t:ItemId").getAttribute("ChangeKey");

Or if "t:ItemId"is a collection:

或者如果"t:ItemId"是一个集合:

 var changeKey = xmlDoc.getElementsByTagName("t:ItemId")[0].getAttribute("ChangeKey");