简体   繁体   English

Javascript 在 html 中有效,但在 .js 文件中无效

[英]Javascript works in html but won't work in .js file

I am very new to JavaScript and have a bit of code that works when included directly in my html file, but when I try and put it into the.js file I am building for my website, it stops working.我是 JavaScript 的新手,有一些代码可以直接包含在我的 html 文件中,但是当我尝试将它放入我正在为我的网站构建的 .js 文件时,它停止工作。

Is the "$" being in the.js file causing the problem? .js 文件中的“$”是否导致了问题?

How do I re-write this code so that it can be used in my JS file?我如何重写这段代码,以便它可以在我的 JS 文件中使用?

<div id="section1" class="dropSection"> 
  <a class="edit top-right">Option 1</a>
  <div class="childSection">
     <div class="splash">item 1</div>
     <div class="splash">item 2</div>
     <div class="splash">item 3</div>
  </div>
</div>

   <script>
   $('body').click(function() {
      $('div.childSection').hide();
        });
      $(".dropSection a").click(function(event) {
          var parent = $(this).parent();
          parent.toggleClass("selected");
          parent.find("div.childSection").toggle();
          parent.find("section-content").toggle();
          event.stopPropagation();
        });
  </script>

EDIT: In the section I have a working script reference to jquery-3.6.1.min.js as well as my personal.js file (which does have other working script in it - they just don't used the $ format)编辑:在本节中,我有一个工作脚本引用 jquery-3.6.1.min.js 以及我的 personal.js 文件(其中确实有其他工作脚本 - 他们只是不使用 $ 格式)

The "$" being in the.js file is not causing the problem. .js 文件中的“$”不会导致问题。 "$" symbol is being used as a shorthand for the jQuery library which also you need to import in your.html file in <head> section. “$”符号用作 jQuery 库的简写,您还需要在<head>部分的 .html 文件中导入该库。

<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

You need to wrap your js code in $(document).ready(function($) , because it ensures that the code inside the function only runs after the DOM is fully loaded and ready. So, your finaly script.js file will be somethig like this. Also you need to import script.js in your html file.您需要将 js 代码包装在$(document).ready(function($)中,因为它确保 function 中的代码仅在 DOM 完全加载并准备就绪后运行。因此,您的最终script.js文件将是像这样的东西。您还需要在 html 文件中导入script.js

$(document).ready(function ($) {
    $("body").click(function () {
        $("div.childSection").hide();
    });
    $(".dropSection a").click(function (event) {
        event.stopPropagation();
        var parent = $(this).parent();
        parent.toggleClass("selected");
        parent.find("div.childSection").toggle();
        parent.find("section-content").toggle();
    });
});

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

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