Javascript 如何使用 jQuery 调用 Bootstrap 警报?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32704027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:07:35  来源:igfitidea点击:

How to call Bootstrap alert with jQuery?

javascriptjquerytwitter-bootstrap

提问by KDX2

Let's say I've the following piece of code:

假设我有以下代码:

<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>

How can I activate it manualy by using jQuery?

如何使用 jQuery 手动激活它?

回答by Malk

Bootstrap uses the inand outclass for visibility. You just need to toggle those classes. Also, if you want to keep the alert around once cancelled you can add a return false to the close.bs.alertevent.

Bootstrap 使用inandout类来实现可见性。你只需要切换这些类。此外,如果您想在取消后保持警报,您可以向close.bs.alert事件添加 return 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