简体   繁体   English

JavaScript在单独的文件中时不起作用

[英]JavaScript not working when is in separate file

I have code: 我有代码:

$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $(".koncecki-web-design").addClass("konecki-scroll");
        $(".top-nav").addClass("show");
        $("#work").addClass("work-margin");
    } else {
        $(".koncecki-web-design").removeClass("konecki-scroll");
        $(".top-nav").removeClass("show");
        $("#work").removeClass("work-margin");
    }
    if (scroll >= 200) {
        $(".top-text").addClass("top-text-scroll");
    } else {
        $(".top-text").removeClass("top-text-scroll");
    }
});

I have this in my index file but i want to have in control.js 我在索引文件中有这个,但是我想在control.js中有

<script type="text/javascript" src="js/control.js"></script> 

When i paste this code to control.js script does not work. 当我将此代码粘贴到control.js脚本时不起作用。

What could be wrong? 有什么事吗

Thanks! 谢谢! Silon 西隆

Be sure to have jQuery included before control.js. 确保在control.js之前包含jQuery。 So 所以

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/control.js"></script>

instead of 代替

<script type="text/javascript" src="js/control.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>

You need to: 你需要:

  1. Check if you including control.js before jquery.js then it would not work move your jquery file to top. 检查是否在jquery.js之前包含control.js,然后将jquery文件移到顶部将不起作用。
  2. DOM is not ready to be worked on so move all your code to $(document).ready() DOM还没有准备好进行工作,因此将所有代码移至$(document).ready()
  3. Or include your control.js just before closing body tag, it will take care of above two points. 或者在关闭body标签之前添加control.js,它将处理以上两点。

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

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