|

为了避免在HTML中显示大量的代码,我们一般选择将js脚本单独放入一个文件中,然后再将js文件导入HTML中,这样可以使得HTML文件更加简洁,本文主要介绍导入js脚本的两种方式分别是:传统导入、模块导入。 首先确认需要导入的js脚本的位置,本文在HTML文件同路径下。
1.传统导入: JS脚本内容: //文件名:example.js
let a="呵呵姑娘"; HTML内容: <!-- example.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./example.js"></script>
<script>
console.log(a);
</script>
</body>
</html>2.模块导入: JS脚本内容: //文件名:example.js
let a="呵呵姑娘";
export {a}; HTML内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import {a} from './example.js';
console.log(a);
</script>
</body>
</html> 推荐:《2021年js面试题及答案(大汇总)》《js教程》 以上就是Javascript中导入js文件的两种方式的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |