通过 JavaScript 动态创建 Bootstrap 警报框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10082330/
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 23:46:11  来源:igfitidea点击:

Dynamically create Bootstrap alerts box through JavaScript

javascripttwitter-bootstrap

提问by ed1t

I'm using Bootstrap 2.0 for my project and I would like to dynamically add Bootstrap alert box in my page (http://twitter.github.com/bootstrap/javascript.html#alerts). I want to do something like:

我正在为我的项目使用 Bootstrap 2.0,我想在我的页面 ( http://twitter.github.com/bootstrap/javascript.html#alerts)中动态添加 Bootstrap 警报框。我想做类似的事情:

bootstrap-alert.warning("Invalid Credentials"); 

回答by periklis

Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)

试试这个(在 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>?

EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js

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

回答by UberNeo

/**
  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);
  }

回答by pvlsgnnks

You can also create a HTML alert template like this:

您还可以创建一个 HTML 警报模板,如下所示:

<div class="alert alert-info" id="alert_template" style="display: none;">
    <button type="button" class="close">×</button>
</div>

And so you can do in JavaScript this here:

所以你可以在这里用 JavaScript 做到这一点:

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

Which is in my opinion cleaner and faster. In addition you stick to Twitter Bootstrap standards when calling fadeIn().

在我看来,这更清洁、更快。此外,您在调用fadeIn().

To guarantee that this alert template works also with multiple calls (so it doesn't add the new message to the old one), add this here to your JavaScript:

为确保此警报模板也适用于多个调用(因此它不会将新消息添加到旧消息),请将其添加到您的 JavaScript 中:

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

So this call removes the span element every time you close the alert via the x-button.

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

回答by Fabrizio

I created this VERY SIMPLE and basic plugin:

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

(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);

Usage is

用法是

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

first plugin EVER and it can be easily made better

第一个插件,它可以很容易地变得更好

回答by Ted

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

今天发现了这个,做了一些调整并结合了其他答案的功能,同时将其更新为 bootstrap 3.x。注意:这个答案需要 jQuery。

In html:

在 HTML 中:

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

In JS:

在JS中:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
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>?

Then you can invoke this either as:

然后你可以调用它:

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

回答by JustCarty

FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.

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

There is a readme there with a more in-depth explanation, but I'll do a quick example below:

那里有一个自述文件,里面有更深入的解释,但我会在下面做一个简单的例子:

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

The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".

上面将创建一个简单的主要警报,其中包含一个包含文本“Some content here”的段落元素。

There are also options that can be set on initialisation.
For your requirement you'd do:

还有一些可以在初始化时设置的选项。
根据您的要求,您可以:

var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());

The rendermethod will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.

render方法将返回一个 HTML 元素,然后可以将其插入到 DOM 中。在这种情况下,我们将它附加到 body 标签的底部。

This is a work in progress library, but it still is in a very good working order.

这是一个正在进行中的库,但它仍然处于非常好的工作状态。

回答by Cirem

回答by Adrian P.

I found that AlertifyJSis a better alternative and have a Bootstrap theme.

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

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

Also have a 4 components: Alert, Confirm, Promptand Notifier.

也有4 个组件AlertConfirmPromptNotifier

Exmaple: JSFiddle

示例JSFiddle

回答by antelove

just recap:

简单回顾一下:

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

代码笔

回答by rom m

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