一般web頁面中,html文件通過標簽script引用js文件。但是js文件之間的引用要通過import/exprot進行導入/導出,同時還要在html文件中對js文件的引用使用type屬性標注。
在下面的例子中,
html頁面
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>Title</title>
</head><body><form><input id="username" name="username" type="text"><input id="age" name="age" type="text"><input id="b1" type="submit" value="提交"><input id="b2" type="button" value="單擊事件"></form><br><br><br><table width="800px" border="1" cellspacing="0" align="center"><tr><th>學號</th><th>姓名</th><th>分數</th><th>評語</th></tr><tr align="center"><th>001</th><th>張三</th><th>90</th><th>優秀</th></tr><tr id='last' align="center"><th>003</th><th>趙四</th><th>85</th><th>良好</th></tr></table><!-- 調用的js文件使用到export,import等高級技能時,必須使用屬性type='module'標注。 --><script src="../../js/常見事件優化/常見事件優化.js" type="module"></script>
</body>
</html>
html調用“常見事件優化.js”文件。
// 導入變量,方法。
import {content, printConsoleLog} from "./打印日志.js";console.log(content);// 定義函數。
let mouseEnter = function (event) {// window.alert('鼠標進入事件');// console.log('鼠標進入事件');printConsoleLog('鼠標進入事件');
};function mouseLeave(event) {// window.alert('鼠標離開事件');// console.log('鼠標離開事件');printConsoleLog('鼠標離開事件');printConsoleLog(event.type);
};const button = document.querySelector('#b1');
button.addEventListener('click', function () {// window.alert('點擊submit按鈕');// console.log('點擊submit按鈕');printConsoleLog('點擊submit按鈕');
});// 根據id獲取控件,綁定事件。
const inputController = document.querySelector('#last');
inputController.addEventListener('mouseenter', mouseEnter);
inputController.addEventListener('mouseleave', mouseLeave);
被導入的“打印日志.js”文件,文件中通過export關鍵字標注導出被調用的方法和變量。
export function printConsoleLog(msg) {console.log(msg);
}export let content = 'abc';