Я пытаюсь научиться использовать Bootstrap и JQuery.Для моего текущего проекта я пытаюсь сделать так, чтобы пользователь мог взаимодействовать с модалами.Я заметил, что фреймворк Bootstrap предлагает использовать его специфические модальныеЯ должен понять, как это реализовать, до тех пор, пока не будет заполнен такой модал.
Скажем, я хочу не допускать добавления одного и того же элемента снова и снова (я просто хотел бы использовать один элемент, чтобы уменьшить дублированиекод), я решил, что хотел бы использовать JQuery, чтобы использовать один мод и заполнять его при любом событии, которое запускается.В этом примере я буду использовать кнопки и события щелчка.
Когда я нажимаю кнопку, она должна заполнить модал, назначенный кнопке, HTML-кодом, предоставленным в событии щелчка.Мне известно, что есть несколько способов добиться этого, например, используя AJAX для получения представления, содержащего HTML, или используя функции JQuery hide()
, clone()
и show()
:
$(document).ready(function() {
//On initialization:
//Store modal initial values so they can be reset when closed:
let modalMediumInit = $(".modal.bs-example-modal-md").html();
let modalLargeInit = $(".modal.bs-example-modal-lg").html();
let modalSmallInit = $(".modal.bs-example-modal-sm").html();
//On modal close:
$(".modal.bs-example-modal-md").on("hidden.bs.modal", function() {
//Reset modal to initial values:
$(".modal.bs-example-modal-md").html(modalMediumInit);
});
$(".modal.bs-example-modal-lg").on("hidden.bs.modal", function() {
//Reset modal to initial values:
$(".modal.bs-example-modal-lg").html(modalLargeInit);
});
$(".modal.bs-example-modal-sm").on("hidden.bs.modal", function() {
//Reset modal to initial values:
$(".modal.bs-example-modal-sm").html(modalSmallInit);
});
$("#my-element").hide();
//On interaction:
$(".controls").on("click", "#my-control", function() {
//Populate modal .modal-body element...
//Currently using JQuery:
let html = $("#my-element").clone();
$(".modal.modal.bs-example-modal-lg .modal-content .modal-body").html(html);
$(".modal.modal.bs-example-modal-lg .modal-content .modal-body #my-element").show();
//Or (AJAX might return some HTML and set it into the html variable):
html = "<p>A very long string containing all my required html</p>";
//$(".modal.modal.bs-example-modal-lg .modal-content .modal-body").html(html); //<-- Uncomment following to see effect.
});
});
#my-element button {
margin-top: 2px;
margin-bottom: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />
<div id="my-element">
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary btn-block">
Foo
</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary btn-block">
Foo
</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary btn-block">
Foo
</button>
</div>
</div>
</div>
<div class="controls">
<button id="my-control" type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
Populate and open...
</button>
</div>
<br />
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-md">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal bs-example-modal-md fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Large modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large modal</button>
<div class="modal bs-example-modal-lg fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg" 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">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Small modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal</button>
<div class="modal bs-example-modal-sm fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm" 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">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JSFiddle
Всякий раз, когда я использую метод JQuery, предоставленный элементчтобы заполнить модал, будет загружен при загрузке страницы (я заметил, что этот элемент также будет отображаться на короткое время, прежде чем он будет скрыт предоставленным кодом JQuery, который мне кажется нежелательным).Будет ли это неправильным решением для заполнения модального Bootstrap?В последнее время я много читаю в AJAX, должен ли я использовать это в этом случае, чтобы загрузить HTML в мой модал?