2012-04-10 1140 views

Respuesta

74

Prueba esto (ver un ejemplo práctico de este código en 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>​ 

EDITAR: En la actualidad hay bibliotecas que simplificar y racionalizar este proceso , como bootbox.js

+4

Para cumplir con los [documentos de arranque] (http://getbootstrap.com/components/#alerts) debe agregar .alert-dismissable a su div. – Keelan

+6

Ejemplo de Twitter bootstrap 3: http://jsfiddle.net/eman86/p4e3y/5/ – Eman

+0

puede'bootstrap_alert = function() {} 'ser atajo a' bootstrap_alert = {} '? –

9

también puede crear una plantilla de alerta HTML así:

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

Y por lo que se puede hacer en Javascript esta aquí:

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

¿Qué está en mi opinión más limpio y más rápido. Además, cumple con los estándares de Twitter Bootstrap al llamar al fadeIn().

Para garantizar que esta plantilla de alerta funciona también con múltiples llamadas (por lo que no tiene que añadir un nuevo mensaje a la anterior), agregar esta aquí para su JavaScript:

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

Así que esto elimina la llamada elemento span cada vez que cierras la alerta mediante el botón x.

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

Tan útil. Gracias ... – Cataclysm

+0

+1 para una respuesta más específica. – Ganesh

+0

¡Excelente! En Bootstrap 3, las alertas son '.alert-success, .alert-info, .alert-warning & .alert-danger' – secretwep

3

Encontré esto hoy, hice algunos ajustes y combiné las características de las otras respuestas mientras las actualicé a bootstrap 3.x. NB: Esta respuesta requiere jQuery.

en HTML:

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

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

A continuación, puede invocar este ya sea como:

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

creé este plugin muy simple y básica:

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

uso es

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

primer plugin nunca y que se puede hacer fácilmente mejor

+0

incluso puede agregar un 'bs_close: function() {$ ('alerta'). Alert ('close');}' – Fabrizio

0

encontré que AlertifyJS es una alternativa mejor y tiene un tema de Bootstrap.

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

también tener un 4 componentes: de alerta, Confirmar, Prompt y notificador.

Exmaple: JSFiddle

0

Fwiw que creó una clase de JavaScript que se puede utilizar en tiempo de ejecución.
Se acabó el GitHub, here.

Hay un readme allí con una explicación más en profundidad, pero voy a hacer un ejemplo rápido a continuación:

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

Lo anterior podría crear una alerta primaria simple con un elemento de párrafo en el interior que contiene el texto "Algunos contenidos aquí".

También hay opciones que se pueden configurar en la inicialización.
Para su requisito que harías:

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

El método render devolverá un elemento HTML, que puede ser insertado en el DOM. En este caso, lo adjuntamos a la parte inferior de la etiqueta de cuerpo.

Esta es una biblioteca en proceso, pero todavía está en muy buen estado de funcionamiento.

Cuestiones relacionadas