setInterval 中的 xml 数据不替换信息

xml data in setInterval not replacing information

本文关键字:替换 信息 数据 中的 xml setInterval      更新时间:2023-09-26

我正在尝试创建一个记分板,该记分板使用 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>

(在我意识到提问者真正想要什么后编辑)

如果您查看数据集,每个游戏都有一个唯一的"id"属性。每次检查XML文档时,我们都会使用该确切的游戏ID更新HTML元素,或者,如果尚不存在此类HTML元素,则创建一个。

JSFiddle

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>