js代码不在外部文件中工作,但在放在同一个html页面时工作文件
我在html页面的页脚中有这段代码
// using jQuery $('video,audio').mediaelementplayer();
上面的代码是在html页面上添加video播放器。
现在我已经创建了一个单独的js文件,其中我已经有一些代码行创建owl滑块,工具提示,数字计数器等。
当我将上面的代码添加到separate js file
它不起作用,相反,当我将它保存在footer of the html page
的footer 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(基本上)应该是这样的:
和你的jquery文件:
jQuery(function($) { // your functions here $('video,audio').mediaelementplayer(); });
您是否有正确链接到页面中的单独js文件,通常位于正文的底部? 它应该看起来像这样:
如果您已正确完成,是否尝试清除浏览器缓存? 您可能需要这样做才能检测新的javascript文件。
你怎么称呼外部js文件?
您必须在外部js文件之前添加引用js。
你必须在document.ready上添加你的function。
您可以等到jQuery满载或ready
。
防爆。
$(document).ready(function($) { // Your code goes here $('video,audio').mediaelementplayer(); });
此代码位于外部js
文件中,然后您需要将该文件包含在HTML中