技术需求:当特定数据行值变化时按间隔刷新该行(附现有代码)
Solution: Refresh Only Changed Rows Periodically
Got it, let's work through this problem to get exactly what you need—refreshing only specific rows when their values change, instead of reloading everything every time. First, I'll fix the small issues in your original code and add the targeted refresh logic. Here's the revised implementation:
<!-- Ensure jQuery is loaded properly --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(document).ready(function() { // Store previous row values to detect changes let previousRowData = {}; // Core function to fetch data and update only changed rows function updateChangedRows() { fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD') .then(res => res.json()) // Parse JSON instead of raw text for easier data handling .then(data => { const exchanges = data.Data; const outputContainer = $('#output'); // First load: render the full table since we have no prior data if (Object.keys(previousRowData).length === 0) { let tableHtml = ` <table style="border-collapse: collapse; width: 100%;"> <thead> <tr> <th style="border: 1px solid #ddd; padding: 8px;">Exchange</th> <th style="border: 1px solid #ddd; padding: 8px;">24h Volume (USD)</th> </tr> </thead> <tbody> `; exchanges.forEach(exchange => { const rowId = `exchange-${exchange.EXCHANGE}`; tableHtml += ` <tr id="${rowId}"> <td style="border: 1px solid #ddd; padding: 8px;">${exchange.EXCHANGE}</td> <td style="border: 1px solid #ddd; padding: 8px;" class="volume-cell">${exchange.VOLUME24HOUR.toLocaleString()}</td> </tr> `; // Save initial volume value for future comparison previousRowData[rowId] = exchange.VOLUME24HOUR; }); tableHtml += '</tbody></table>'; outputContainer.html(tableHtml); } else { // Subsequent loads: compare each row's value to detect changes exchanges.forEach(exchange => { const rowId = `exchange-${exchange.EXCHANGE}`; const currentVolume = exchange.VOLUME24HOUR; const previousVolume = previousRowData[rowId]; // Only update the row if the value changed if (currentVolume !== previousVolume) { // Update the specific volume cell $(`#${rowId} .volume-cell`).text(currentVolume.toLocaleString()); // Update stored data to match current value previousRowData[rowId] = currentVolume; // Optional: Add a visual highlight to the changed row $(`#${rowId}`).css('background-color', '#f7f9fc').fadeOut(800).fadeIn(800, () => { $(`#${rowId}`).css('background-color', ''); }); } }); } }) .catch(err => console.error('Failed to fetch data:', err)); } // Run once on page load, then repeat every 5 seconds (adjust interval as needed) updateChangedRows(); setInterval(updateChangedRows, 5000); }); </script> <div id="output"></div>
Key Improvements & Explanations:
- JSON Parsing: Switched from
res.text()tores.json()so we can easily access specific data fields (like exchange volume) instead of dealing with raw text. - Change Detection: We store previous row values in
previousRowData(keyed by row ID). On each refresh, we compare current values to stored ones to identify changes. - Targeted DOM Updates: Instead of replacing the entire
#outputcontainer, we only update the specific cell that changed. This is faster and smoother for users. - First Load Handling: On the initial page load, we render the full table since there's no prior data to compare against.
- Visual Feedback (Optional): Added a fade-in/out highlight for changed rows to help users spot updates at a glance.
- Cleaned Redundant Code: Removed the unused
randomnumbervariable and fixed the incomplete jQuery script link from your original code.
Customization Tips:
- If your target "specific data row" isn't exchange volume, replace
VOLUME24HOURwith the data field you need to track. - Adjust the refresh interval by changing
5000(milliseconds) to your desired frequency (e.g.,1000for 1 second). - Modify the HTML table structure and CSS to match your existing page design.
内容的提问来源于stack exchange,提问作者sindhoorit avm
相关产品推荐
相关产品推荐

