![](/img/trans.png)
[英]how can i link my javascript file with html???? I think i have linked properly but not working?
[英]I have linked a jquery file but I can't use it
我已將我的 HTML 鏈接到 jquery 但是當我在 Microsoft Edge 中運行它時,它會輸出
“Help.js:1 未捕獲的 ReferenceError:$ 未在 Help.js:1(匿名)@Help.js 中定義:
代碼:
$(document).ready(function(){ $(".navBar").hover(function(){ $(this).css("border","2px solid black") }) })
navBar{ display: flex; position: sticky; top:0; padding: 20px; border: none; width: 100%; justify-content: center; background-color: gainsboro; z-index: 2; } #Title{ color: black; font-family: monospace; }
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>A Random Website</title> </head> <body> <script src="style.js"></script> <script src="https://code.jquery.com/jquery-latest.js"></script> <div class="navBar"> <div> <h1 id="Title">SomeRandomWebsite</h1> </div> </div> </body> </html>
這是因為您在 jQuery 加載之前使用$
。
// Instead of:
//...
<script src="style.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
//...
// Use this:
// ...
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="style.js"></script>
// ...
並將這些腳本標記移動到結束</body>
標記之前的行。 IE:
// ...
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="style.js"></script>
</body>
</html>
在你的head tag
中添加腳本,首先加載 jquery 然后你的自定義 style.js 文件。
此外,將defer
屬性添加到您的腳本中。
存在時的延遲屬性,指定當頁面完成解析時執行腳本。 您可以閱讀有關延遲的更多信息
$(document).ready(function() { $(".navBar").hover(function() { $(this).css("border", "2px solid black") }) })
.navBar { display: flex; position: sticky; top: 0; padding: 20px; border: none; width: 100%; justify-content: center; background-color: gainsboro; z-index: 2; } #Title { color: black; font-family: monospace; }
<html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>A Random Website</title> <script src="https://code.jquery.com/jquery-latest.js" defer></script> <script src="style.js" defer></script> <link rel="stylesheet" href="style.css"> </head> <body> <div class="navBar"> <div> <h1 id="Title">SomeRandomWebsite</h1> </div> </div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.