頁面加載時調用 $("#myModal").modal("show"),模態框不顯示,無報錯。
腳本位于 <head> 中,執行時 <body> 內的 #myModal 元素尚未渲染,jQuery 選擇器返回空集合,調用無效。
將調用包裹在 **DOM 就緒事件** 中:
<script>
$(function() { // 等同於 $(document).ready()
$("#myModal").modal("show");
});
</script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="modal fade" id="myModal">...</div>
<script>
$(function() {
$("#myModal").modal("show");
});
</script>
</body>
</html>
https:// (原代碼 // 在本地文件協議下無效)。<body> 末尾或包裹在 $(function(){}) 中。