提问者:小点点

如何用新数据改变旧数据,而不是在HTML中使用socket.io在旧数据下面添加一个新数据?


我正在使用以下代码使用socket.io将数据加载到web页面:

io.on('connection', socket => {
    setInterval(() => {
        socket.emit('temp', ({temp1, temp2, gasSensor}))
        
      }, 15000)
})

httpServer.listen(3000, () => {
    console.log('go to http://localhost:3000')
})

HTML文档:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Temperatura ESP32</title>
</head>
<style>
    body {
      background-color: linen;
    }

    p {
        color: blue;
        text-align: center;
        font-size: 200%;
    }
    </style>
<body>
    
    <p id="events"></p>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const $events = document.getElementById('events')

        const newItem = (content) => {
          const item = document.createElement('p')
          item.innerText = content
          return item
        }

        const socket = io()

        socket.on('connect', () => {
          $events.appendChild(newItem('Temperature and gas amount:'))
        })

        socket.on('temp', ({temp1, temp2, gasSensor}) => {
     $events.appendChild(newItem(temp1 + 'C°    '+ temp2 + 'C°    ' + gasSensor ))
          })
          
    </script>
</body>
</html>

所以这段代码是在旧数据下面每15000毫秒不断地添加一个新数据到web页面,但是我想用新的数据替换旧的数据(覆盖)。

这是代码的当前结果


共2个答案

匿名用户

每次“temp”事件发生时,您将创建一个新的p元素,而不是这样:

null

const $events = document.getElementById('events')

const newItem = (content) => {
  const item = document.createElement('p')
  item.innerText = content
  return item
}

socket.on('temp', ({temp1, temp2, gasSensor}) => {
  $events.appendChild(newItem(temp1 + 'C°    '+ temp2 + 'C°    ' +     gasSensor ))
})

匿名用户

您可以使用replaceWith

socket.on('connect', () => {
  $events.appendChild(newItem('Temperature and gas amount:'));
  $events.appendChild(newItem("")); //empty default value
})

socket.on('temp', ({temp1, temp2, gasSensor}) => {
  $($events).children().last().replaceWith(newItem(temp1 + 'C°    '+ temp2 + 'C°    ' + gasSensor ));
})