[英]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 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(基本上)應該是這樣的:
<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.