我对这段代码有疑问:
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
(function update() {
$.ajax({
type: 'GET',
url: "http://192.168.4.2/home/api/stato/ambiente/living",
dataType: "json",
success: renderList
}).then(function() {
setTimeout(update, 200);
});
})();
function renderList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$.each(list, function(index, data) {
if (data.stato ==1) {
$('#statoList').append('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_on.png " + '</div>');
$('#Switch').append('<button type="button">' + " OFF " + '</button>');
}
else {
$('#statoList').append('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_off.png " + '</div>');
$('#Switch').append('<button type="button">' + " ON " + '</button>');
}
});
}
</script>
</head>
<body>
<div id="statoList"></div>
<div id="Switch"></div>
</body>
</html>
我希望每 200 毫秒执行一次 DIV 刷新,但问题是每次都会在前一个 DIV 下方创建一个新的 DIV。
我该如何解决这个问题?
谢谢。
最佳答案
append 函数不符合您的期望,我建议您使用 .html(),这样它会将您的所有代码(新 div)转换为 html 代码
function renderList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$.each(list, function(index, data) {
if (data.stato ==1) {
$('#statoList').html('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_on.png " + '</div>');
$('#Switch').html('<button type="button">' + " OFF " + '</button>');
}
else {
$('#statoList').html('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_off.png " + '</div>');
$('#Switch').html('<button type="button">' + " ON " + '</button>');
}
});
}
关于javascript - Ajax 创建新的 DIV 而不是刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040051/