高级天气应用紧急告警显示故障:已接收紧急疏散告警但无法展示
Let's walk through the key issues preventing your alerts from showing up, even though the callback is firing:
1. You're not adding the alert element to the DOM
This is the biggest blocker: you create the alert div, but never attach it to any part of the page. The element exists in memory, but the browser has no idea to render it on the screen.
2. Incorrect class attribute assignment
DOM elements use className (not class) to set CSS classes—class is a reserved keyword in JavaScript, so direct assignment won't apply your styles. For cleaner class management, you could also use classList.add() instead.
3. Height property set the wrong way
Setting alert.height = '500px' doesn't apply the height as a visible CSS style. You need to target the element's style object to modify layout properties.
4. Typo in the innerHTML variable
You reference payload.source in the HTML string, but your function parameter is named info—this will throw a reference error, which might be silently breaking the rest of the function execution.
Fixed displayPush Function
Here's the corrected version that addresses all these issues:
async function displayPush(info){ if (info.type === 'emergency'){ let alert = document.createElement('div') // Use className to apply CSS classes alert.className = 'relative isolate flex items-center overflow-hidden bg-red-900 text-neutral-50' // Set height via the style object alert.style.height = '500px' alert.id = 'emergency-alert-' + info.id // Fix the variable typo from payload.source to info.source alert.innerHTML = ` <p style="font-size: 20px;">${info.message}</p> <br> <p style="font-size: 10px;">${info.locations}</p> <br> <p style="font-size: 5px;">${info.source}</p> ` // Attach the alert to the DOM (append to body, or a specific container) // Replace with your target container if you have one, e.g., document.getElementById('alert-container') document.body.appendChild(alert) } }
Extra Tips
- If you have a dedicated container for alerts (like a div with id
alert-container), append the alert there instead ofdocument.bodyfor better layout control. - Add
try/catcherror handling to catch silent errors that might stop execution—logging these to the console can help with future debugging.
内容的提问来源于stack exchange,提问作者user32587615

