js code is not working in an external file, but wo

2019-07-27 04:52发布

I have this code in the footer of my html page

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

the above code is adding video player on the html page.

Now I have created a separate js file in which I have already have some line of code which is creating owl sliders, tooltips, number counters etc.

When I add the above code into that separate js file it does not work, instead when I keep it in the footer of the html page it works fine.

5条回答
在下西门庆
2楼-- · 2019-07-27 05:17

You may wait until jQuery is full loaded or ready.

Ex.

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

This code goes in external js file, then you need to include the file in the HTML

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

查看更多
狗以群分
3楼-- · 2019-07-27 05:19

Do you have a proper link to the separate js file in your page, generally at the bottom of the body? It should look something like this:

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

If you've done that properly, have you tried clearing your browser cache? You may need to do that to detect new javascript files.

查看更多
女痞
4楼-- · 2019-07-27 05:24

Try placing your code within $(function(){ ... }. This will execute when the DOM is loaded (currently your code is being executed before jQuery is loaded, if you check the JavaScript console, you will see an error something like $ is not defined)

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

or

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

You can read about what that is doing here. $(function() is the same as $( document ).ready()

查看更多
该账号已被封号
5楼-- · 2019-07-27 05:30

your html(basically) should look like this:

<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>

and your jquery file:

jQuery(function($) {
    // your functions here
    $('video,audio').mediaelementplayer();
});
查看更多
smile是对你的礼貌
6楼-- · 2019-07-27 05:30

How do you call your external js file ?
You must add your references js before your external js file.
you must add your function on document.ready.

查看更多
登录 后发表回答