简体   繁体   English

HTML 负载 jQuery function

[英]HTML load jQuery function

Can anyone please help me to understand, why I'm not able to load my jQuery functions(stored in script.js) using HTML(index.htm)谁能帮我理解,为什么我无法使用 HTML(index.htm)加载我的 jQuery 函数(存储在 script.js 中)

Following are the codes of:以下是以下代码:

script.js脚本.js

 $.get("./Components/head.htm", function(data) { $("head").append(data); }); $("#logo").on("error", function() { $(this).hide(); $("#name").show(); }); $("#search").keyup(function() { alert($(this).val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <:DOCTYPE html> <html lang="en"> <head> <title>SAM</title> <script src="https.//code.jquery.com/jquery-3.5.1.min.js"></script> <script src="./script.js"></script> </head> <body> <div id="header"> <div id="brand"> <img src="./Static/Logo.png" id="logo"> <h1 hidden id="name">SAM Store</h1> </div> <div> <input type="search" id="search" list="suggest"> <datalist id="suggest"> <option value="Laptop"></option> <option value="Mouse"></option> <option value="Keyboard"></option> <option value="Speaker"></option> <option value="Earphone"></option> </datalist> </div> <script> </script> </div> </body> </html>

[NB: Functions are working if I'm adding $.get function in index.htm and importing script.js using it, but they are not working if I'm referencing script.js on index.htm & importing $.get function. [注意:如果我在 index.htm 中添加 $.get function 并使用它导入 script.js,则函数正在工作,但如果我在 index.htm 上引用 script.js 并导入 $.get function,它们将不起作用. Also, the browser is successfully able to load the script.js in both of these cases]此外,在这两种情况下,浏览器都能够成功加载 script.js]

When ever you use jquery always load the code inside an on ready statement, otherwise they will not always load on time.当您使用 jquery 时,始终将代码加载到就绪语句中,否则它们将不会始终按时加载。

$( document ).ready(function() {

  $.get("Components/head.htm", function(data) {
    $("head").append(data);
  });

  $("#logo").on("error", function() {
    $(this).hide();
    $("#name").show();
  });

  $("#search").keyup(function() {
    alert($(this).val());
  });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM