2017-01-10 4 views
5

У меня проблема с близким модальным в bootstrap. Когда я открываю модальные окна с данными (изменение модального контента на основе кнопки запуска). Это пример http://getbootstrap.com/javascript/#modalsBootstrap modal close button

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Open modal for @mdo</button> 
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@fat">Open modal for @fat</button> 
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Open modal for @getbootstrap</button> 
...more buttons... 

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"> 
    <div class="modal-dialog" role="document"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
     <h4 class="modal-title" id="exampleModalLabel">New message</h4> 
     </div> 
     <div class="modal-body"> 
     <form> 
      <div class="form-group"> 
      <label for="recipient-name" class="control-label">Recipient:</label> 
      <input type="text" class="form-control" id="recipient-name"> 
      </div> 
      <div class="form-group"> 
      <label for="message-text" class="control-label">Message:</label> 
      <textarea class="form-control" id="message-text"></textarea> 
      </div> 
     </form> 
     </div> 
     <div class="modal-footer"> 
     <button type="button" class="btn btn-default" id="btnclose" data-dismiss="modal">Close</button> 
     <button type="button" id="btnsend" class="btn btn-primary">Send message</button> 
     </div> 
    </div> 
    </div> 
</div> 

Это нормально, но если я закрываю модальную и открыты в другой кнопке, когда нажмите на кнопку отправить печать в консоли журнал значение получателя первых модальный и этого модального. Но мне нужно только напечатать последнее значение получателя. Я не понимаю, почему события стека предыдущего модального закрытия. Это мой JQuery код, для обеих кнопок:

$('#exampleModal').on('show.bs.modal', function (event) { 

    var button = $(event.relatedTarget) // Button that triggered the modal 
    var recipient = button.data('whatever') // Extract info from data-* attributes 
    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). 
    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. 
    var modal = $(this) 
    modal.find('.modal-title').text('New message to ' + recipient) 
    modal.find('.modal-body input').val(recipient) 

    $("#btnsend").one("click", function(){ 
     console.log('Pinchado') 
     console.log(recipient) 
    }) 

    $("#btnclose").one("click", function(){ 
     console.log('Cerrando...') 
    }) 

    $('#exampleModal').on('hidden.bs.modal', function (e) { 
     console.log('Cerrada'); 
    }) 

    }) 

Спасибо вы очень много, и я надеюсь, что кто-нибудь может мне помочь. https://jsfiddle.net/DTcHh/28480/

+0

Для меня печатает только последний модальный получателя. – Troyer

ответ

4

Это старый способ, которым вы или вы можете сказать обычный способ, которым вы это делаете. Тем не менее у него есть ответы. просто привяжите скрытые и кликовые события за пределами связывания события show.

$('#exampleModal').on('show.bs.modal', function(event) { 
 

 
    var button = $(event.relatedTarget) // Button that triggered the modal 
 
    var recipient = button.data('whatever') // Extract info from data-* attributes 
 
    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). 
 
    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. 
 
    var modal = $(this) 
 
    modal.find('.modal-title').text('New message to ' + recipient) 
 
    modal.find('.modal-body input').val(recipient) 
 

 
    
 

 
}) 
 
    
 
$("#btnsend").on("click", function() { 
 
    console.log('Pinchado') 
 
    console.log(recipient) 
 
    }) 
 

 
    $("#btnclose").on("click", function() { 
 
    console.log('Cerrando...') 
 
    }) 
 

 
    $('#exampleModal').on('hidden.bs.modal', function(e) { 
 
    console.log('Cerrada'); 
 
    })
<!-- Latest compiled and minified CSS --> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css"> 
 

 
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> 
 

 

 
<!-- jQuery library --> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 

 
<!-- Latest compiled JavaScript --> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script> 
 

 

 

 

 
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Open modal for @mdo</button> 
 
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@fat">Open modal for @fat</button> 
 
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Open modal for @getbootstrap</button> 
 
...more buttons... 
 

 
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"> 
 
    <div class="modal-dialog" role="document"> 
 
    <div class="modal-content"> 
 
     <div class="modal-header"> 
 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span> 
 
     </button> 
 
     <h4 class="modal-title" id="exampleModalLabel">New message</h4> 
 
     </div> 
 
     <div class="modal-body"> 
 
     <form> 
 
      <div class="form-group"> 
 
      <label for="recipient-name" class="control-label">Recipient:</label> 
 
      <input type="text" class="form-control" id="recipient-name"> 
 
      </div> 
 
      <div class="form-group"> 
 
      <label for="message-text" class="control-label">Message:</label> 
 
      <textarea class="form-control" id="message-text"></textarea> 
 
      </div> 
 
     </form> 
 
     </div> 
 
     <div class="modal-footer"> 
 
     <button type="button" class="btn btn-default" id="btnclose" data-dismiss="modal">Close</button> 
 
     <button type="button" id="btnsend" class="btn btn-primary">Send message</button> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

Ниже современный способ сделать это. Вы можете обратиться к this link за дополнительной информацией о способе динамического создания модально.

function open_modal(name) { 
 

 
    var message = $('#frm_1'); 
 
    BootstrapDialog.show({ 
 
    title: 'New message to ' + name, 
 
    message: $('#frm_1'), 
 
    onshown : function() { 
 
     $('#recipient-name').val(name); 
 
    }, 
 
    onhide : function(dialog) { 
 
     $('#hidden-div').append(message); 
 
    }, 
 
    buttons: [{ 
 
     label: 'Close', 
 
     action: function(dialog) { 
 
     dialog.close(); 
 
     } 
 
    }, { 
 
     label: 'Send message', 
 
     cssClass: 'btn btn-primary', 
 
     action: function(dialog) { 
 
     // Do whatever send message does, here 
 
     } 
 
    }] 
 
    }); 
 

 

 

 
}
<!-- Latest compiled and minified CSS --> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css"> 
 

 
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> 
 

 

 
<!-- jQuery library --> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 

 
<!-- Latest compiled JavaScript --> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script> 
 

 
<button type="button" class="btn btn-primary" onclick="open_modal('@mdo')">Open modal for @mdo</button> 
 
<button type="button" class="btn btn-primary" onclick="open_modal('@fat')">Open modal for @fat</button> 
 
<button type="button" class="btn btn-primary" onclick="open_modal('@getbootstrap')">Open modal for @getbootstrap</button> 
 

 

 

 
<div id="hidden-div" style="display : none"> 
 

 
    <form id="frm_1"> 
 
    <div class="form-group"> 
 
     <label for="recipient-name" class="control-label">Recipient:</label> 
 
     <input type="text" class="form-control" id="recipient-name"> 
 
    </div> 
 
    <div class="form-group"> 
 
     <label for="message-text" class="control-label">Message:</label> 
 
     <textarea class="form-control" id="message-text"></textarea> 
 
    </div> 
 
    </form> 
 

 

 
</div>

+0

удивительный ответ ... спасибо! –

0

Большое спасибо за ваш ответ. Работать сейчас. В первом примере есть ошибка. Нужна она, удалите var, чтобы сделать вары глобальными. С работает хорошо.

$('#exampleModal').on('show.bs.modal', function(event) { 

      button = $(event.relatedTarget) // Button that triggered the modal 
      recipient = button.data('whatever') // Extract info from data-* attributes 
      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). 
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. 
      var modal = $(this) 
      modal.find('.modal-title').text('New message to ' + recipient) 
      modal.find('.modal-body input').val(recipient) 
    }) 
1

В Bootstrap 3.3.7 эта работа для меня:

$('#myModal').trigger('click.dismiss.bs.modal')