JavaScript动态ID问题:Socket.io获取新数据后更新元素innerHTML
Complete Implementation to Update Dynamic IDs with Socket.io
Got it, let's walk through a full, working solution for your scenario. You already have the dynamic IDs set up in EJS—now we just need to wire up Socket.io to update those elements whenever new data comes in.
1. Backend Setup (Node.js/Express + Socket.io)
First, make sure you have socket.io installed (npm install socket.io). Then set up your Express server to integrate with Socket.io:
const express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const app = express(); const server = http.createServer(app); // Initialize Socket.io (adjust CORS settings if your frontend is on a different origin) const io = new Server(server, { cors: { origin: "http://localhost:3000", // Replace with your actual frontend URL methods: ["GET", "POST"] } }); // Configure EJS as the view engine app.set('view engine', 'ejs'); // Serve your index page with initial price data app.get('/', (req, res) => { // Replace this with your actual data source (database, API, etc.) const result = Array.from({ length: 100 }, (_, i) => ({ price: (Math.random() * 100).toFixed(2) })); res.render('index', { result }); }); // Example: Simulate real-time price updates (replace with your actual data trigger) setInterval(() => { // Pick a random index and generate a new price const targetIndex = Math.floor(Math.random() * 100); const newPrice = (Math.random() * 100).toFixed(2); // Send the update to all connected clients io.emit('priceUpdate', { index: targetIndex, price: newPrice }); }, 2000); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
2. Frontend (index.ejs)
Update your EJS file to include the Socket.io client script and add the logic to listen for updates:
<!DOCTYPE html> <html> <head> <title>Real-Time Price Updates</title> <style> /* Optional: Style to highlight updated prices */ .updated { background-color: #fef3c7; } </style> </head> <body> <table> <tr> <% for (var i = 0; i < 100; i++) { %> <th> <span class="Pr" id="price<%=i%>">$<%= result[i]["price"] %></span> </th> <% } %> </tr> </table> <!-- Include Socket.io client (auto-served by your backend) --> <script src="/socket.io/socket.io.js"></script> <script> // Connect to the Socket.io server const socket = io(); // Listen for price update events from the server socket.on('priceUpdate', (data) => { const { index, price } = data; // Target the element with the dynamic ID const priceElement = document.getElementById(`price${index}`); // Guard clause to avoid errors if the element doesn't exist if (!priceElement) return; // Update the price and add a visual highlight priceElement.innerHTML = `$${price}`; priceElement.classList.add('updated'); setTimeout(() => { priceElement.classList.remove('updated'); }, 1000); }); </script> </body> </html>
Key Details to Note
- Data Structure: The server sends an object with
indexandprice—this is critical because it tells the frontend exactly which element to update, no guesswork needed. - Error Prevention: We check if the target element exists before modifying it, which avoids console errors if the server sends an index outside your 0-99 range.
- User Feedback: The optional
updatedclass adds a temporary highlight, making it obvious to users when a price changes. - CORS: If your frontend and backend are on different domains, make sure to set the correct
originin the Socket.io server config to avoid connection issues.
That's all! When you run the server, you'll see prices update automatically every 2 seconds (or whenever your server emits the priceUpdate event with real data).
内容的提问来源于stack exchange,提问作者user9504869
相关产品推荐
相关产品推荐

