警报框Bootstrap关闭按钮已消失

问题描述

这是通过单击按钮输出的期望。文本旁边有一个关闭按钮。

<div class="alert alert-success alert-dismissible">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <strong>Successfully Alerted</strong> 
</div>

这是我的代码。当我单击按钮时,警报框的关闭按钮消失了。

<div class="alert alert-dismissible w-50" style="display: none;">
  <button type="button" class="close" data-dismiss="alert">&times;</button>

</div>
<button class="btn btn-info abtn">Alert</button>

<script type="text/javascript">
  $(document).ready(function() {
    showAlert();
  });

  function showAlert() {
    $('.abtn').click(function() {
      $('.alert').addClass("alert-success");
      $('.alert').text("Successfully Alerted").show();
    });

  }

</script>

我这样做是因为我想根据情况以不同的颜色显示不同的消息。知道为什么会这样以及如何解决吗?

解决方法

您需要使用.append()而不是.text来使Xalert出现在您的text

.text()将替换您alert div中的所有内容

实时演示:

$(document).ready(function() {
  $('.abtn').click(function() {
    $('.alert').addClass("alert-success");
    $('.alert').append("Successfully Alerted").show();
  });
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<div class="alert alert-dismissible w-50" style="display: none;">
  <button type="button" class="close" data-dismiss="alert">&times;</button>

</div>
<button class="btn btn-info abtn">Alert</button>