我正在阅读使用JavaScript的XML文件,这部分工作,因为我正在获取数据。下面是XML文件:HTML <input>按钮消失点击
<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()
功能不会被调用,但是当我点击change
按钮时,change()
功能不会被调用。
那就是'document.write'呢,它覆盖'document'! – adeneo 2014-09-25 17:38:51
所以我想在每次按下按钮时重新创建按钮,如果我希望事情能够按照这种方式工作? – 2014-09-25 17:40:07
最好不要使用'document.write' – 2014-09-25 17:40:45