2017-08-10 38 views
1

我試圖在頁面通過按鈕單擊加載後(在下面的文檔就緒而不是點擊)加載模式到頁面。該模式是通過克隆另一個模式並將該克隆附加到DOM來創建的。模態節點出現在DOM中,但是在給出.modal()命令時模態不會打開。我創建了一個簡單的codepen,顯示我的代碼,並在下面顯示。使用JavaScript和克隆節點添加Bootstrap Modal

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

在你的codepen上,你還沒有添加引導程序所需的'jQuery',如果'jQuery'添加了它似乎正在工作https://jsbin.com/pamiqac/edit?html,js,output – azs06

+0

在我的代碼筆示例調整我的引導程序和jQuery腳本的序列解決了這個問題。在我的實際項目中,我調整了腳本被調用的位置並解決了我的問題。 @ azs06如果你提出了一個答案,建議改變我的腳本發佈的順序,我會檢查它作爲答案。 – nejohannsen

+0

@ azs06如果你提出了一個答案,建議改變我的腳本發佈的順序,我會檢查它作爲答案。 – nejohannsen

回答

1

在您codepen你還沒有加入這是由引導需要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{ 
 
\t 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> \t 
 
<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突出克隆元素。