javascript 'getElementsByTagName' 出现未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24070741/
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 02:08:21  来源:igfitidea点击:

'getElementsByTagName' comes up undefined

javascripthtmlxmlxmlhttprequestgetelementsbytagname

提问by puppies_pidgeons

I am working on a content flow that displays images based on xml content. I'm building it as a site, so it's html and javascript, and for some unknown reason-and believe me I've combed it over with as fine of a toothed comb as I can- my javascript just isn't loading my xml (thats what I'm fairly certain the problem is, but I could be wrong) and it's throwing me the error that 'getElementsByTagName' is null. Now currently i havent built in the full functionality, I just wanted to test the xml by having it read out as text so bear with me here.

我正在研究基于 xml 内容显示图像的内容流。我正在将它构建为一个站点,因此它是 html 和 javascript,并且出于某种未知原因 - 相信我,我已经用尽可能细的齿梳梳理了它 - 我的 javascript 只是没有加载我的 xml (这就是我相当确定的问题所在,但我可能是错的)并且它向我抛出了“getElementsByTagName”为空的错误。现在我还没有内置完整的功能,我只是想通过将它作为文本读出来测试 xml,所以请耐心等待。

loadXMLDoc.js:

加载XMLDoc.js:

function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}

my internal java in the html:

我在 html 中的内部 java:

<script>
xmlDoc = loadXMLDoc("test.xml");
    var x = xmlDoc.getElementsByTagName("song");
    for (i=0; i<x.length; i++);
    {
     var a = (x[i].getElementsByTagName("source")[0].childnodes[0].nodeValue);
     var b = (x[i].getElementsByTagName("artist")[0].childnodes[0].nodeValue);
     var c = (x[i].getelementsByTagName("title")[0].childnodes[0].nodeValue);
     var par = '<img class= "item" href ="#" ondblclick = "confirm()" src ="' +'" "title="' +b+ '"-"'+ c+ ' " />';
     document.getElementById("demo").innerHTML += par;
     }
</script>

and the full error:

和完整的错误:

Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined album.html:24 (anonymous function)

未捕获的类型错误:无法读取未定义专辑.html:24 的属性“getElementsByTagName”(匿名函数)

and for funsies my xml sample:

和我的 xml 示例:

<song>
<source>imgs/Beck.jpg</source>
<title>Modern Guilt</title>
<artist>Beck</artist>
</song>

Hopefully I covered all that would be needed, I know its probably something silly, but I can't nail it down.

希望我涵盖了所有需要的内容,我知道这可能有些愚蠢,但我无法确定。

回答by Adrien Vinches

First of all you have a ";" that shouldn't be here after your for loop:

首先你有一个“;” 在你的 for 循环之后不应该在这里:

for (i=0; i<x.length; i++);
    {

it should be

它应该是

for (i=0; i<x.length; i++) {

because what is happening here is that you for loop iterates over the elements of x but without executing your body.

因为这里发生的事情是您的 for 循环遍历 x 的元素但不执行您的主体。

Secondly, your

其次,你的

var c = (x[i].getelementsByTagName("title")[0].childnodes[0].nodeValue);

contains a typo, it should be getElementsByTagName with a e capitalized

包含一个错字,它应该是 getElementsByTagName 并且 ae 大写

Here is the code I used and it is working correctly:

这是我使用的代码,它工作正常:

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>

<div id="demo"></div>

<script>
var loadXMLDoc = function (filename) {
        var xhttp;
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.open("GET",filename,false);
        xhttp.send();

        if (xhttp.readyState === 4 && xhttp.status === 200) {
            return xhttp.responseXML;
        }
        return {error : 'file not found'};

    },
    xmlDoc = loadXMLDoc("test.xml"),
    testObj = xmlDoc,
    x = testObj.getElementsByTagName("song");
for (i=0; i<x.length; i++) {
    var objectElem = x[i];
     var a = (objectElem.getElementsByTagName("source")[0].textContent),
         b = (objectElem.getElementsByTagName("artist")[0].textContent),
         c = (objectElem.getElementsByTagName("title")[0].textContent),
         par = '<img class="item" href="#" ondblclick="confirm()" src="'+ a +'" title="' +b+ '-'+ c+ '" />';
     console.log(par);
     document.getElementById("demo").innerHTML += par;
 }
</script>

</body>

</html>

and here is my test.xml (place in the same folder as the above code):

这是我的 test.xml(与上面的代码放在同一个文件夹中):

<songlist>
    <song>
        <source>imgs/Beck.jpg</source>
        <title>Modern Guilt</title>
        <artist>Beck</artist>
    </song>
    <song>
        <source>imgs/Beck2.jpg</source>
        <title>Modern Guilt2</title>
        <artist>Beck2</artist>
    </song>
</songlist>

回答by Rialgar

Just in case it actually IS a issue with asynchronous requests, this is how you do it asynchronously (I took the liberty to declare xhttp locally, too):

以防万一它实际上是异步请求的问题,这就是您异步执行的方式(我也冒昧地在本地声明了 xhttp):

function loadXMLDoc(filename, callback)
{
    var xhttp;
    if (window.XMLHttpRequest)
    {
        xhttp=new XMLHttpRequest();
    }
    else // code for IE5 and IE6
    {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET",filename,true);
    xhttp.onreadystatechange = function()
    {
        if(xhttp.readyState === 4)
        {
            callback(xhttp.responseXML);
        }
    }
    xhttp.send();
}

loadXMLDoc("test.xml", function(xmlDoc)
{
    var x = xmlDoc.getElementsByTagName("song");
    for (i=0; i<x.length; i++)
    {
        var a = (x[i].getElementsByTagName("source")[0].childnodes[0].nodeValue);
        var b = (x[i].getElementsByTagName("artist")[0].childnodes[0].nodeValue);
        var c = (x[i].getElementsByTagName("title")[0].childnodes[0].nodeValue);
        var par = '<img class= "item" href ="#" ondblclick = "confirm()" src ="' +'" "title="' +b+ '"-"'+ c+ ' " />';
        document.getElementById("demo").innerHTML += par;
    }
});

But make sure the result of the web-request has the Content-Type header of text/xml, or resultXML will not be set. In any case you might want to have a look at the documentation: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

但是请确保 web 请求的结果具有 的 Content-Type 标头text/xml,否则将不会设置 resultXML。无论如何,您可能想查看文档:https: //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Edit: also fixed your typos mentioned by Adrien Vinches.

编辑:还修复了 Adrien Vinches 提到的错别字。