我用加载我的xml文件的js制作html。 现在我有一个按钮,每次单击都会移到下一个节点。 我如何制作previus按钮,每次单击该按钮都可以返回。
<html>
<head>
<title>ReadingXmlFile</title>
<link href="StyleSheet.css" rel="stylesheet" />
</head>
<body>
<center><h1>XML FILE</h1></center>
<input id="next" type="button" value="LoadXml" onclick="readXML()" />
<input id="previous" type="button" value="previus" onclick="readXML()" />
<div>
<p id="demo"></p>
</div>
<script type="text/javascript">
var i = 0;
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'XMLFile.xml', false);
xml.send();
var xmlData = xml.responseXML;
if (xmlData) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var det = xmlData.getElementsByTagName("mydetails");
var name = det[i].getElementsByTagName("name")[0].firstChild.data;
var city = det[i].getElementsByTagName("city")[0].firstChild.data;
var bio = det[i].getElementsByTagName("bio")[0].firstChild.data;
document.getElementById("demo").innerHTML = "Name: " + name + "<br>" + "City: " + city + "<br>" + "Bio: " + bio;
i++;
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
好的,这里有一些更改以正确支持Next / Previous。
请注意:可能有语法错误,因为没有XML来运行这个打击。抱歉。
var i = 0;
var xmlData = undefined;
const setInnerHTML = (position) => {
if (xmlData) {
let det = xmlData.getElementsByTagName("mydetails");
let name = det[position].getElementsByTagName("name")[0].firstChild.data;
let city = det[position].getElementsByTagName("city")[0].firstChild.data;
let bio = det[position].getElementsByTagName("bio")[0].firstChild.data;
document.getElementById("demo").innerHTML = "Name: " + name + "<br>" + "City: " + city + "<br>" + "Bio: " + bio;
}
};
// Add a document load event, load the XML just once
document.addEventListener('DOMContentLoaded', function() => {
readXml(() => {
// Show initial data when XML has loaded
setInnerHTML(i);
});
// Add our click events for previous and next
document.querySelector('#next').addEventListener('click', (evet) => {
i++;
setInnerHTML(i);
});
document.querySelector('#previous').addEventListener('click', (evet) => {
i--;
setInnerHTML(i);
});
});
// This function only loads XML now.
function readXML(onComplete) {
let xml = new XMLHttpRequest();
xml.open('GET', 'XMLFile.xml', false);
xml.onload = function() {
if (xml.status >= 200 && xml.status < 400) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
if (onComplete) onComplete();
};
xml.send();
}
}
<html>
<head>
<title>ReadingXmlFile</title>
<link href="StyleSheet.css" rel="stylesheet" />
</head>
<body>
<center>
<h1>XML FILE</h1>
</center>
<input id="next" type="button" value="LoadXml" />
<input id="previous" type="button" value="previus" />
<div>
<p id="demo"></p>
</div>
</body>
</html>