通过JavaScript动态创建Bootstrap警告框

61
10个回答

88

尝试这个(在jsfiddle中查看此代码的工作示例:http://jsfiddle.net/periklis/7ATLS/1/

<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
        }

$('#clickme').on('click', function() {
            bootstrap_alert.warning('Your text goes here');
});
</script>

编辑:现在有一些库可以简化和优化这个过程,例如bootbox.js


4
根据 Bootstrap 文档 的要求,您应该向 div 元素中添加 .alert-dismissable 类。 - user1544337
can'bootstrap_alert = function() {} 可以简写为 bootstrap_alert = {} 吗? - Vitali Climenco

44
/**
  Bootstrap Alerts -
  Function Name - showalert()
  Inputs - message,alerttype
  Example - showalert("Invalid Login","alert-error")
  Types of alerts -- "alert-error","alert-success","alert-info","alert-warning"
  Required - You only need to add a alert_placeholder div in your html page wherever you want to display these alerts "<div id="alert_placeholder"></div>"
  Written On - 14-Jun-2013
**/

  function showalert(message,alerttype) {

    $('#alert_placeholder').append('<div id="alertdiv" class="alert ' +  alerttype + '"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')

    setTimeout(function() { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs


      $("#alertdiv").remove();

    }, 5000);
  }

太好了!在Bootstrap 3中,警告框的类别分别为.alert-success, .alert-info, .alert-warning & .alert-danger - secretwep
1
但是,如果您在删除此项之前创建另一个项目,则会产生ID冲突。 - Jan Kaifer

9
您可以创建一个类似这样的HTML警告模板:
<div class="alert alert-info" id="alert_template" style="display: none;">
    <button type="button" class="close">×</button>
</div>

因此,您可以在JavaScript中进行以下操作:

$("#alert_template button").after('<span>Some text</span>');
$('#alert_template').fadeIn('slow');

我认为这种方法更干净、更快。而且在调用 fadeIn() 时,你遵循了 Twitter Bootstrap 的标准。

为了确保此警告模板也适用于多次调用(因此不会将新消息添加到旧消息中),请将以下内容添加到你的 JavaScript 中:

$('#alert_template .close').click(function(e) {
    $("#alert_template span").remove();
});

因此,每次通过x按钮关闭警报时,此调用将删除span元素。


7
我创建了这个非常简单和基础的插件:

我创建了这个非常简单和基础的插件:

(function($){
    $.fn.extend({
        bs_alert: function(message, title){
            var cls='alert-danger';
            var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            if(typeof title!=='undefined' &&  title!==''){
                html+='<h4>'+title+'</h4>';
            }
            html+='<span>'+message+'</span></div>';
            $(this).html(html);
        },
        bs_warning: function(message, title){
            var cls='alert-warning';
            var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            if(typeof title!=='undefined' &&  title!==''){
                html+='<h4>'+title+'</h4>';
            }
            html+='<span>'+message+'</span></div>';
            $(this).html(html);
        },
        bs_info: function(message, title){
            var cls='alert-info';
            var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            if(typeof title!=='undefined' &&  title!==''){
                html+='<h4>'+title+'</h4>';
            }
            html+='<span>'+message+'</span></div>';
            $(this).html(html);
        }
    });
})(jQuery);

使用方法为:

<div id="error_container"></div>
<script>
$('#error_container').bs_alert('YOUR ERROR MESSAGE HERE !!', 'title');
</script>

第一个插件,可以轻松改进


你甚至可以添加一个函数 bs_close: function(){$('.alert').alert('close');} - Fabrizio

4

简要回顾:

$(document).ready(function() {

    $('button').on( "click", function() {

      showAlert( "OK", "alert-success" );

    } );

});

function showAlert( message, alerttype ) {

    $('#alert_placeholder').append( $('#alert_placeholder').append(
      '<div id="alertdiv" class="alert alert-dismissible fade in ' +  alerttype + '">' +
          '<a class="close" data-dismiss="alert" aria-label="close" >×</a>' +
          '<span>' + message + '</span>' + 
      '</div>' )
    );

    // close it in 3 secs
    setTimeout( function() {
        $("#alertdiv").remove();
    }, 3000 );

}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        
<button onClick="" >Show Alert</button>
      
<div id="alert_placeholder" class="container" ></div>

codepen


4

今天发现了这个问题,进行了一些调整并结合了其他答案的特点,同时将其更新为Bootstrap 3.x版本。注意:此答案需要jQuery。

HTML中:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

在JS中:
<script>
//https://dev59.com/2Wkw5IYBdhLWcg3wKneb
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');

  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>​

然后您可以这样调用:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

2

FWIW,我创建了一个JavaScript类,可以在运行时使用。
它在GitHub这里

那里有一个自述文件,其中有更详细的解释,但下面我将做一个快速的示例:

var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());

上述内容将创建一个简单的主要警告,其中包含一个段落元素,其中包含文本“Some content here”。
还可以在初始化时设置选项。
对于您的要求,您可以执行以下操作:
var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());
render方法将返回一个HTML元素,可以将其插入到DOM中。在这种情况下,我们将其追加到body标签的底部。 这是一个正在进行的库,但它仍然处于非常良好的工作状态。

1

1
function bootstrap_alert() {
        create = function (message, color) {
            $('#alert_placeholder')
                .html('<div class="alert alert-' + color
                    + '" role="alert"><a class="close" data-dismiss="alert">×</a><span>' + message
                    + '</span></div>');
        };
        warning = function (message) {
            create(message, "warning");
        };
        info = function (message) {
            create(message, "info");
        };
        light = function (message) {
            create(message, "light");
        };
        transparent = function (message) {
            create(message, "transparent");
        };
        return {
            warning: warning,
            info: info,
            light: light,
            transparent: transparent
        };
    }

0

我发现AlertifyJS是一个更好的选择,并且有Bootstrap主题。

alertify.alert('Alert Title', 'Alert Message!', function(){ alertify.success('Ok'); });

同时还有4个组件: 警告框确认框提示框通知器

例子: JSFiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接