如何使用jQuery调用Bootstrap alert

How to call Bootstrap alert with jQuery?

本文关键字:Bootstrap alert 调用 jQuery 何使用      更新时间:2023-09-26

假设我有以下一段代码:

<div class="alert alert-info fade in" id="bsalert">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  <strong>Info!</strong> This alert box could indicate a neutral informative or action
</div>

如何使用jQuery手动激活它?

Bootstrap使用inout类来实现可见性。你只需要切换这些类。此外,如果您想在取消后保持警报,您可以向close.bs.alert事件添加返回false。

function toggleAlert(){
    $(".alert").toggleClass('in out'); 
    return false; // Keep close.bs.alert event from removing from DOM
}
$("#btn").on("click", toggleAlert);
$('#bsalert').on('close.bs.alert', toggleAlert)
<link rel="stylesheet" type="text/css"  href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<button id="btn">Toggle</button>
<div class="alert alert-info fade out" id="bsalert">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  <strong>Info!</strong> This alert box could indicate a neutral informative or action
</div>
<div>
    content