繁体   English   中英

js代码不在外部文件中工作,但在放在同一个html页面时工作文件

[英]js code is not working in an external file, but works file when placed in the same html page

我在html页面的页脚中有这段代码

<script type="text/javascript">
// using jQuery
$('video,audio').mediaelementplayer();
</script>

上面的代码是在html页面上添加视频播放器。

现在我已经创建了一个单独的js文件,其中我已经有一些代码行创建了owl滑块,工具提示,数字计数器等。

当我将上面的代码添加到separate js file它不起作用,相反,当我将它保存在footer of the html pagefooter of the html page它可以正常工作。

尝试将你的代码放在$(function(){ ... } 。这将在加载DOM时执行(当前你的代码是在加载jQuery之前执行的,如果你检查JavaScript控制台,你会看到类似的错误$ is not defined

 $(function(){
     $('video,audio').mediaelementplayer();
 });

要么

 $( document ).ready(function() {
     $('video,audio').mediaelementplayer();
 });

你可以在这里阅读一下这是做什么的。 $(function()$( document ).ready()

你的HTML(基本上)应该是这样的:

<html>
  <head>
  </head>
  <body>
     <!-- html code here -->

     <!-- add jquery lib -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
     <!-- your script -->
     <script src="you/file/path.js"></script>
  </body>
</html>

和你的jquery文件:

jQuery(function($) {
    // your functions here
    $('video,audio').mediaelementplayer();
});

您是否有正确链接到页面中的单独js文件,通常位于正文的底部? 它应该看起来像这样:

<script type="text/javascript" src="/joyride_odoo_models/static/js/scripts.js"/>

如果您已正确完成,是否尝试清除浏览器缓存? 您可能需要这样做才能检测新的javascript文件。

你如何调用外部js文件?
您必须在外部js文件之前添加引用js。
你必须在document.ready上添加你的功能。

您可以等到jQuery满载或ready

防爆。

$(document).ready(function($) {
    // Your code goes here
    $('video,audio').mediaelementplayer();
});

此代码位于外部js文件中,然后您需要将该文件包含在HTML中

<script type="text/javascript" src="path/to/your/js/file"></script>

暂无
暂无

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

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