【发布时间】:2014-11-20 14:12:30
【问题描述】:
我正在使用 JavaScript 读取 XML 文件,这部分在我获取数据时工作。这是 XML 文件:
<bookstore>
<book category="romance">
<title lang="en">Everyday Italian</title>
<author>Giada</author>
<year>2005</year>
<price>30,00</price>
</book>
<book category="cooking">
<title lang="en">Cook Book</title>
<author>Manado</author>
<year>2012</year>
<price>44,00</price>
</book>
<book category="drama">
<title lang="en">Intrigue</title>
<author>L'amion</author>
<year>2002</year>
<price>29,99</price>
</book>
</bookstore>
现在我使用 JavaScript 在表格中显示该数据。另外,我添加了两个<input> 按钮,每个按钮都有一个onclick 属性来调用特定函数。一键调用change(),另一键调用remove()。
这是 HTML 页面和 JavaScript 的代码:
<html>
<head>
<title>Index</title>
<script type="text/javascript">
function loadXMLDoc(dname) {
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // for IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send();
return xhttp.responseXML;
}
// function to print all book titles
function printTitles() {
var xmlDoc = loadXMLDoc('bookstore.xml');
var elements = xmlDoc.getElementsByTagName('title')
document.write('<table border="1"><tr><th>Title</th></tr>');
for(i = 0; i < elements.length; i++) {
document.write("<tr>");
document.write(
"<td>" + elements[i].childNodes[0].nodeValue + "</td>");
document.write("</tr>")
}
document.write("</table>");
}
// function to change the first book title
function change(text) {
var xmlDoc = loadXMLDoc('bookstore.xml');
var elements = xmlDoc.getElementsByTagName('title');
var title = elements[0].childNodes[0];
title.nodeValue = text;
printTitles(elements);
}
// function to remove the first book
function remove(node) {
var xmlDoc = loadXMLDoc('bookstore.xml');
var rem = xmlDoc.getElementsByTagName(node)[0];
xmlDoc.documentElement.removeChild(rem);
printTitles(elements);
}
printTitles();
</script>
</head>
<body>
<input type="button" value="change" onclick="change('WORKS')"/>
<input type="button" value="remove" onclick="remove('book')"/>
</body>
</html>
当我单击change 按钮时,两个按钮都消失了。
当我点击remove按钮时,只有remove按钮消失。
这是我页面的所有 3 种状态(我无法上传照片,因为我没有代表):
http://postimg.org/image/5lrwf7rcz/
现在,我已经搜索了答案,而 this question 或 this question 答案对我没有帮助。我找不到丢失的结束标签,返回 false 并没有改变任何东西。
更新:我在 Chrome 上运行了调试器,当我点击 remove 按钮时,remove() 函数永远不会被调用但是当我点击 @987654340 @ 按钮,change() 函数会被调用。
【问题讨论】:
-
这就是
document.write所做的,它会覆盖document! -
所以如果我想让事情以这种方式工作,我想在每次按下按钮时重新创建按钮?
-
最好不要使用
document.write -
不,你应该不使用
document.write!!! -
阅读了
document.write之后,你应该熟悉DOM操作方法createElement、createTextNode和appendChild。
标签: javascript html xml dom-events html-input