You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ajax天气项目中用JavaScript根据数据值插入SVG图标

解决方案

你可以通过条件判断生成对应的SVG图标字符串,再把它插入到页面内容里。以下是修改后的代码,我以温度和风速为例做了演示:

let info = document.querySelector('#weather-info'); 
document.querySelector('#city').addEventListener('change', function () {
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${this.value}&appid=2d89e68411ec3ef60dfdae66530bb266&lang=el&units=metric`)
        .then(res => res.json())
        .then((data) => {
            // 温度对应的SVG图标
            let tempSvg = '';
            if (data.main.temp > 25) {
                // 高温太阳图标(内联SVG)
                tempSvg = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>';
            } else if (data.main.temp < 10) {
                // 低温雪花图标(内联SVG)
                tempSvg = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 17.58A5 5 0 0 0 18 8h-1.26A8 8 0 1 0 4 16.25"/><line x1="16" y1="1" x2="16" y2="4"/><line x1="8" y1="1" x2="8" y2="4"/><line x1="12" y1="1" x2="12" y2="4"/></svg>';
            }

            // 风速对应的SVG图标
            let windSvg = '';
            if (data.wind.speed > 10) {
                // 大风图标(内联SVG)
                windSvg = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.59 4.59A2 2 0 1 1 11 8H2m10.59 11.41A2 2 0 1 0 14 16H2m15.73-8.27A2.5 2.5 0 1 1 19.5 12H2"/></svg>';
            }

            // 整合图标与原有内容
            info.innerHTML = `
                ${tempSvg} ${data.weather[0].description},<br>
                <strong>${data.main.temp}C<sup>o</sup></strong>,<br><br>
                ${windSvg} <span>Ταχύτητα Ανέμου</span> ${data.wind.speed} <span>Km/h</span>,
            `;
        })
})

关键说明:

  • 内联SVG:直接把SVG代码写入字符串,无需外部链接,避免加载或跨域问题。你可以按需修改SVG的尺寸、颜色、路径,替换成符合需求的图标。
  • 条件逻辑:通过if/else判断数值范围,生成对应SVG字符串后,插入到模板字符串中即可。
  • 格式优化:用反引号包裹的模板字符串支持直接换行,让代码和页面结构更易读。

你可以根据项目需求,调整温度、风速的阈值,或者新增湿度等其他数据的判断条件,插入对应的图标。

内容的提问来源于stack exchange,提问作者tasos83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:15:50