我试图通过点击按钮在页面加载后向页面添加模态(在下面我在文档就绪而不是单击时做了)。通过克隆另一个模态然后将克隆附加到DOM来创建模态。模态节点出现在DOM中,但在给出.modal()命令时,模态不会打开。我创建了一个简单的codepen来显示我的代码,并在下面显示它。
Codepen:https://codepen.io/anon/pen/YxQrZG
HTML:
<div id="LocalModalArea">
<div class="modal fade" id="exampleModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div id="myModalLabel" class="sideLineHeader">
<h2><span>Modal Header</span></h2>
</div>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
JS:
$("Document").ready(function () {
var newModal = $("#exampleModel").clone(true, true);
newModal.attr("id", "NewModelId")
$('#LocalModalArea').append(newModal)
$("#NewModelId").modal("show")
});
答案 0 :(得分:1)
在您的codepen上,您尚未添加bootstrap所需的jQuery
。
$("Document").ready(function () {
var newModal = $("#exampleModel").clone(false, true);
newModal.attr("id", "NewModelId")
$('#LocalModalArea').append(newModal);
$("#NewModelId").addClass('super-red');
$("#NewModelId").modal("show")
});
.super-red{
background-color: darkred;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="LocalModalArea">
<div class="modal fade" id="exampleModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div id="myModalLabel" class="sideLineHeader">
<h2><span>Modal Header</span></h2>
</div>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
注意,我添加了额外的css以突出显示克隆元素。