我正在尝试使用setInterval创建一个刷新其xml数据的记分板,但是当我使用它时,信息会一遍又一遍地显示在其下方,而不是替换第一次显示的数据。我如何获取信息来替换自己而不是一遍又一遍地复制自己?
<script type="text/javascript">
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
setInterval(function() {
xmlDoc=loadXMLDoc("http://gd2.mlb.com/components/game/win/year_2014/month_12/day_11/miniscoreboard.xml");
var x=xmlDoc.getElementsByTagName("game");
for (i=0;i<x.length;i++){
var gameStatus = x[i].getAttribute('status');
document.write(gameStatus + "<br>");
}
}, 3000);
</script>
答案 0 :(得分:0)
(在我意识到提问者真正想要的东西之后编辑)
如果查看数据集,每个游戏都有一个唯一的“id”属性。每当我们检查XML文档时,我们将使用该确切的游戏ID更新HTML元素,或者,如果还没有这样的HTML元素,则创建一个。
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
setInterval(function() {
xmlDoc=loadXMLDoc("http://gd2.mlb.com/components/game/win/year_2014/month_12/day_11/miniscoreboard.xml");
var games = xmlDoc.getElementsByTagName("game");
// For every game...
for (i = 0; i < games.length; i++) {
var gameStatus = games[i].getAttribute('status');
var gameID = games[i].getAttribute("id");
// If no HTML element with that game ID exists, create one.
if (! document.getElementById(gameID)) {
var newGameElement = document.createElement("p");
// The <p> element will contain the game status
newGameElement.textContent = gameStatus;
// And its ID will be the game ID, so we can find the <p> later on
newGameElement.id = gameID;
// This is where we store our game statuses
var gameStatusContainer = document.getElementById("game-status");
// Add the new game element to the status container
gameStatusContainer.appendChild(newGameElement);
}
// If the HTML element with that game ID already exists, update it.
else {
document.getElementById(gameID).textContent = gameStatus;
}
} } );
<div id="game-status">
</div>