前提、実現したいこと
htmlのhead内で自分の使いたいremodalとdatatableというライブラリを読み込んでいたところから、js/script.js内でこれら2つを読み込むようにしたいのですが、そうすると下記のようにエラーが出ます。ライブラリが読めなくなったのだと思います。
$(...).DataTable is not a function
具体的にはこの正常に動くHTML、JSを…
html
1<head> 2 <link rel="stylesheet" href="css/remodal.css" /> 3 <link rel="stylesheet" href="css/remodal-default-theme.css" /> 4 <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> 5 <script src="./js/remodal.js"></script> 6 <script src="./js/datatables.min.js"></script> 7 <script src="./js/script.js"></script> 8 <meta charset="UTF-8" /> 9 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 10 <meta http-equiv="X-UA-Compatible" content="ie=edge" /> 11 <title>Document</title> 12</head> 13 14<body> 15 <a id="remodalOn" href="#modal">Call the modal with data-remodal-id="modal"</a> 16 <div class="remodal" data-remodal-id="modal"> 17 <button data-remodal-action="close" class="remodal-close"></button> 18 <h1>Remodal</h1> 19 <table id="example" class="display" style="width:100%"> 20 <thead> 21 <tr> 22 <th>Name</th> 23 <th>Position</th> 24 <th>Office</th> 25 <th>Age</th> 26 <th>Start date</th> 27 <th>Salary</th> 28 </tr> 29 </thead> 30 <tbody> 31 <tr> 32 <td>Herrod Chandler</td> 33 <td>Sales Assistant</td> 34 <td>San Francisco</td> 35 <td>59</td> 36 <td>2012-08-06</td> 37 <td>$137,500</td> 38 </tr> 39 <tr> 40 <td>Rhona Davidson</td> 41 <td>Integration Specialist</td> 42 <td>Tokyo</td> 43 <td>55</td> 44 <td>2010-10-14</td> 45 <td>$327,900</td> 46 </tr> 47 </tbody> 48 <tfoot> 49 <tr> 50 <th>Name</th> 51 <th>Position</th> 52 <th>Office</th> 53 <th>Age</th> 54 <th>Start date</th> 55 <th>Salary</th> 56 </tr> 57 </tfoot> 58 </table> 59 </div> 60</body>
javascript
1$(document).ready(function () { 2 $('#example').DataTable(); 3});
下記のように変更します。
headタグ内のremodal,datatableのscriptタグは取り払いました。
このおかげで、HTML内の<script src="./js/script.js"></script>の下の行に
コンソールを見てもしっかりheadタグ内にscriptタグが追加されていますが、何故dataTableが使えないのか分かりません。
javascript
1$(function(){ 2 var scripts = ["js/datatables.min.js", "js/remodal.js"]; 3 for (let index = 0; index < scripts.length; ++index) { 4 var script = document.createElement("script"); 5 script.src = scripts[index]; 6 // htmlの<script src="./js/script.js"></script>より前にscriptタグを書き込む 7 document.querySelector("head > script:nth-child(4)").after(script, document.querySelector('head > script:nth-child(4)')) 8 } 9}); 10 11$(document).ready(function () { 12 $('#example').DataTable(); 13});
試したこと
script.jsで、配列の中をremodal.jsのみにすると、エラーなく動いてくれます。
datatableは動かせませんがモーダルは出せます。
どうすれば良いのでしょう?
補足情報(FW/ツールのバージョンなど)
datatablesの入手元:
https://datatables.net/download/

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/10/07 05:05