gpt4 book ai didi

javascript - 如何从函数或变量创建带有 src 属性的 id?

转载 作者:行者123 更新时间:2023-12-02 21:49:32 24 4
gpt4 key购买 nike

我有一个常见的javascript函数来根据PM2.5值获取源图像位置。以下代码不起作用:

<!DOCTYPE html>
<html>
<body>
<p>Finding the aqiicon.</p>
<p id="#aqiicono"></p>

<script>
var aqiicon = "";
var pm25o = 12.0;
// aqiicon = pm25toicon(pm25o);
$("#aqiicono").attr("src", pm25toicon(pm25o));
</script>

<script>
function pm25toicon(pm25) {
if (pm25 < 12.1) {
return "'img/aqi1.png'";
} else if (pm25 < 35.5) {
return "'img/aqi2.png'";
} else if (pm25 < 55.5) {
return "'img/aqi3.png'";
} else if (pm25 < 150.5) {
return "'img/aqi4.png'";
} else if (pm25 < 250.5) {
return "'img/aqi5.png'";
} else {
return "'img/aqi6.png'";
}
}
// document.getElementById("demo").innerHTML = pm25toicon(300);
</script>
</body>
</html>

函数 pm25toicon 接收 PM2.5 值并返回图标的适当位置,然后我尝试通过以下语句将源属性分配给 id:

$('#aqiicono').attr('src', pm25toicon(pm25o));

感谢任何建议。

最佳答案

您的脚本中有一些错误,这里有一个建议:

  • 首先,当页面正确加载 Jquery 时,您应该调用您的函数
  • 第二你不应该输入任何返回“'”,否则你的img将看起来像:
  • 第三您尝试在<p>内加载图像将其编辑为img这是代码

    寻找 aqiicon。

    <script>
    var aqiicon = "";
    var pm25o = 12.0;

    function pm25toicon(pm25) {
    if (pm25 < 12.1) {
    return "img/aqi1.png";
    } else if (pm25 < 35.5) {
    return "img/aqi2.png";
    } else if (pm25 < 55.5) {
    return "img/aqi3.png";
    } else if (pm25 < 150.5) {
    return "img/aqi4.png";
    } else if (pm25 < 250.5) {
    return "img/aqi5.png";
    } else {
    return "img/aqi6.png";
    }
    }

    // Replace src when document is loaded
    $(document).ready(function() {
    $("#aqiicono").attr("src", pm25toicon(pm25o));
    });
    </script>

关于javascript - 如何从函数或变量创建带有 src 属性的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60161331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com