从函数或变量创建具有src属性的ID,如何?

问题描述 投票:0回答:3

我有一个通用的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));

赞赏任何建议。

javascript html id
3个回答
1
投票

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

  • First,当用Jquery正确加载页面时,应调用函数
  • Second您不应放置任何返回“'”,否则,您的img将看起来像是:
  • Third

  • 您正试图在<p>中加载图像,将其编辑为img这是代码

    查找徽标。

<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>


0
投票

更新了一点代码。


0
投票

再次感谢。这是你们两个建议的工作代码:

© www.soinside.com 2019 - 2024. All rights reserved.