为了避免在html中显示大量的代码,我们一般选择将js脚本单独放入一个文件中,然后再将js文件导入html中,这样可以使得html文件更加简洁,本文主要介绍导入js脚本的两种方式分别是:传统导入、模块导入。
首先确认需要导入的js脚本的位置,本文在HTML文件同路径下。
1.传统导入:
JS脚本内容:
//文件名:example.js let a="呵呵姑娘";
HTML内容:
立即学习“Java免费学习笔记(深入)”;
<!-- 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文件的两种方式的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号