我正在閱讀使用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