0

我从教程中复制了以下代码,但仍然无法弄清楚我是否在某个地方犯了错误,或者它是否与浏览器支持有关。提前感谢您向我指出发生的事情!

<html>
<head>
<script type="text/javascript">

function loadXMLDoc(dname)
{   
    if(window.XMLHttpRequest)
    {
        xhttp = new XMLHttpRequest();
    }
    else
    {
        xttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
}

function change(text)
{
    var xmlDoc = loadXMLDoc("dom.xml");
    var x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];

    x.nodeValue = text;

    var y = xmlDoc.getElementsByTagName("title");
    for(i=0; i<y.length; i++) 
    {
        document.write(y[i].childNodes[0].nodeValue+"<br />");
    }
}

function remove(node)
{
    xmlDoc = loadXMLDoc("dom.xml");
    var y = xmlDoc.getElementsByTagName(node)[0];

    xmlDoc.documentElement.removeChild(y);
    alert("The element "+node+" has been removed!");
}

function prove(u)
{
    var x = xmlDoc.getElementsByTagName(u);
    for (i=0; i<x.length; i++)
    {
        document.write(x[i].childNodes[0].nodeValue);
        document.write("<br />");
}

</script>
</head>
<body>
    <input type="button" value="remove" onclick="remove('book')" />
    <input type="button" value="prove it" onclick="prove('book')" />
</body>

</html>

- - - - - - 更新 - - - - - - - - - - - - -

这是一个可能有帮助的 XML 文件:

<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="cooking">
        <title lang="en">Book 2</title>
        <author>Giada</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="cooking">
        <title lang="en">Book 3</title>
        <author>Giada</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
</bookstore>
4

3 回答 3

1

I think the problem might be because of document.write

Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page.

Also there is a } missing after the for statement of prove function

Try using innerHTML on a div or some html element to overcome this issue.

Other than that I don't find any issues with your code

于 2012-05-17T06:38:42.300 回答
0

该脚本正在寻找一个名为“dom.xml”的文件

如果您将该文件放在与上述页面相同的目录中,您将得到不同的结果。

于 2012-05-17T00:03:41.233 回答
0

看起来您缺少最后一个函数证明或 for 循环的括号。

你也可能想声明

var xmlDoc = loadXMLDoc("dom.xml");

在每个函数之外,或将其添加到provide()

于 2012-05-17T00:12:48.903 回答