如何使用jQuery动态更改SVG圆填充颜色的颜色

时间:2018-07-24 06:30:17

标签: javascript jquery

我想动态更改SVG元素的圆圈的颜色。如何根据AJAX调用响应中获得的值动态更改圆圈的颜色?

HTML:

<tr>
  <td style="width: 33.3333%; text-align: center;">
    <svg height="100" width="100">
      <circle id="parking_slot" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="green" />
    </svg>
  </td>
</tr>

JavaScript:

$(document).ready(function() {
  $.ajax({
    url: 'url',
    type: 'GET',
    data: {
      format: 'json'
    },
    success: function(response) {
      if (response.field1 < 50) {
        $("#field1").text("car is parked");
        $("#parking_slot").fill("red");
      } else {
        $("#field1").text("car is not parked");
        $("#parking_slot").fill("green");
      }
    },
    error: function() {
      $('#errors').text("There was an error processing your request. Please try again.");
    }
  });
});

1 个答案:

答案 0 :(得分:1)

像这样使用:

$("#parking_slot").css("background-color", "red");