#javascript #twitter-bootstrap-3 #bootstrap-modal
#javascript #twitter-bootstrap-3 #bootstrap-модальный
Вопрос:
У меня есть 2 ссылки (добавить и отредактировать форму клиента), которые запускают один и тот же загрузочный режим. Мой вопрос в том, как этот один и тот же модальный загрузчик обнаруживает, что он находится по ссылке Add или Edit link?
Мой текущий код
<a href="" class="btn btn-default btn-rounded mb-4" data-toggle="modal" data-target="#modalCustomerForm">
Add New Customer
</a>
$('#modalCustomerForm').on('shown.bs.modal', function () {
$(this).find('form')[0].reset();
})
Ответ №1:
Используйте relatedTarget
свойство event
объекта для доступа к элементу, который вызвал модальное открытие
$('#exampleModal').on('shown.bs.modal', function(e){
const buttonId = e.relatedTarget.id;
$(this).find('.modal-body').text(`Button id = ${buttonId}`);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" ></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" ></script>
<!-- Button trigger modal -->
<button id="btn_1" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Modal Button 1
</button>
<button id="btn_2" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Modal Button 2
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">amp;times;</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>