我对此代码有疑问:
<!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。
我该如何解决这个问题?
谢谢。
答案 0 :(得分:6)
追加功能不适合你所期望的我建议您使用.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>');
}
});
}
答案 1 :(得分:0)
如果在追加
之前每个类型empty()
都有多个容器
$('#statoList').empty();
$.each(list, function(index, data) {
if (data.stato ==1) {...