Aeris Weather Alerts API无返回时如何显示默认提示文本?
解决方案
你只需在现有代码的if判断后添加else分支,当无预警数据时设置目标元素的内容为默认文本即可。以下是修改后的完整代码:
window.onload = () => { const target = document.getElementById('alerts'); const aeris = new AerisWeather('CODE', 'PASSWORD'); const request = aeris.api().endpoint('alerts').place('SDZ047').filter('county').limit(3); request.get().then((result) => { const reports = result.data; if (reports.length > 0) { let html = ''; reports.forEach((details) => { html += ` <div class="cardalert"> <div class="cardalert-body" style="background-color:#${details.details.color || '000000'};"> <div class="alertmessage"> <p><img class="iconalert" src="${details.details.color || 'N/A'}.gif"></p> <p class="textalert">${details.details.name || ''}<br><span>Issued: ${aeris.utils.dates.format(new Date(details.timestamps.issued * 1000), 'MM/dd/yyyy h:mm a')} - Expires: ${aeris.utils.dates.format(new Date(details.timestamps.expires * 1000), 'MM/dd/yyyy h:mm a')}</span></p> </div> </div> <br><p class="bodytext">${details.details.body}</p><br> </div> `; }); target.innerHTML = html; } else { // 无预警时显示默认文本 target.innerHTML = '<p style="text-align:center; padding:1rem; color:#666;">No Weather Alerts</p>'; } }); };
修改说明:
- 新增
else分支,当reports.length === 0(即API返回空数组)时,直接给target元素设置包含默认文本的HTML内容。 - 给默认文本添加了简单内联样式(居中、内边距、灰色文字),你可以根据页面样式需求调整,或替换为自定义CSS类名。
- 修正了原代码中多余的
"和未闭合的</font>标签(无对应<font>标签),避免HTML结构错误。
内容的提问来源于stack exchange,提问作者Tater
相关产品推荐
相关产品推荐

