JQuery - 根据数值更改范围的背景图像

时间:2015-08-23 14:50:09

标签: javascript jquery html

我一直在尝试更改跨度的背景图像,该跨度具有由PHP打印的数值。正如我在FireBug中看到的那样,代码正在运行,但图像没有加载,我几乎可以肯定路径是正确的。我做错了什么?

$(function () {
    var score = parseInt($('#score').text().trim());
    var color = 'red';
    if (!isNaN(score)) {
        if (score >= 40) {
            color = 'orange';
        }
        if (score >= 60) {
            backgroundimage = 'url(images/+.png)';
        }
        $('#score').css('background-image', backgroundimage);
    }
});
<div class="nota-puntuacion">
   <span id="score">
     85 <!--Value Printed by PHP-->
   </span>
</div>

2 个答案:

答案 0 :(得分:0)

URL中的加号被解释为空格。您可以将其URL编码为%2b

backgroundimage = 'url(images/%2b.png)';

答案 1 :(得分:0)

可能你想要这个:

&#13;
&#13;
$(function () {
  changeSpanScore = function (score) {
    bg = {};
    if (score > 0)
      if (score < 25) {
        bg.color = "#f00";
        bg.image = "images/img-1.png";
      } else if (score < 50) {
        bg.color = "#0f0";
        bg.image = "images/img-2.png";
      } else if (score < 75) {
        bg.color = "#00f";
        bg.image = "images/img-3.png";
      } else {
        bg.color = "#fff";
        bg.image = "images/img-4.png";
      }
    else {
      bg.color = "";
      bg.image = "";
    }
    $("#score").html(score).css({
      "background-color": bg.color,
      "background-image": bg.image
    });
  };
});
&#13;
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<p>Enter number and press Enter.</p>
<input type="text" onkeyup="if (event.keyCode == 13) changeSpanScore(this.value);" />
<br /<br /><br />
<div class="nota-puntuacion">
  <span id="score">
    85 <!--Value Printed by PHP-->
  </span>
</div>
&#13;
&#13;
&#13;

在您的情况下,如果您在图片中使用保留字,则需要对其进行编码,因此请将代码更改为:

backgroundimage = 'url(images/%2b.png)';