通过JQuery.append追加html实体

时间:2018-01-19 15:34:13

标签: javascript jquery

我知道有这样的问题,但解决方案对我不起作用。

我想像这样附加Bootstrap消息

但我无法将HTML实体(×)插入实体。

$(function() {
  var errors = {
    "error1": "message1",
    "error2": "message2"
  }

  $.each(errors, function(name, message) {
      var $span = $('<span/>', {
        text: "&#215;"
      });
      var $button = $('<button/>', {
        "class": "close"
      });
      var $alert = $('<div/>', {
        "class": "alert alert-danger alert-dismissible",
        text: message
      });
      $('#error-box').append($alert.append($button.append($span)));
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="error-box">
</div>

1 个答案:

答案 0 :(得分:2)

您可以在此使用html代替text

&#13;
&#13;
$(function() {


  var errors = {
    "error1": "message1",
    "error2": "message2"
  }

  $.each(errors, function(name, message) {
      var $span = $('<span/>', {
        html: "&#215;"
      });
      var $button = $('<button/>', {
        "class": "close"
      });
      var $alert = $('<div/>', {
        "class": "alert alert-danger alert-dismissible",
        text: message
      });
      $('#error-box').append($alert.append($button.append($span)));
  });
});
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="error-box">
</div>
&#13;
&#13;
&#13;