?主函数
<!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>事件绑定封装</title>
</head>
<body>
<input id="ipt1" type="text" />
<hr>
<input id="ipt2" type="text" />
<hr>
<select id="slt1">
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>
</body>
<script src="../jquery.min.js"></script>
<script type="module">
import bindEventCommon from './js/bindEventCommon.js'
$(function() {
const inputItemIdList = [
"ipt1",
"ipt2",
"slt1"
];
bindEventCommon(inputItemIdList);
})
</script>
</html>
???事件绑定的共通函数
async function bindEventCommon(itemIdList) {
const importModule = [];
for (const itemId of itemIdList.values()) {
importModule.push(import(`./${itemId}Event.js`))
}
let eventObjectList = [];
try {
eventObjectList = await Promise.all(importModule);
} catch (error) {
console.error('要导入的模块不存在,请检查ID名称或者模块名称!');
return;
}
for (const [index, itemId] of itemIdList.entries()) {
$(`#${itemId}`).on(eventObjectList[index].default);
}
}
export default bindEventCommon;
?各个项目所对应的事件封装函数 ipt1Event.js
const ipt1EventObject = {
focus: (event) => {
console.log("ipt1的focus()方法执行了");
},
click: (event) => {
console.log("ipt1的click()方法执行了");
}
}
export default ipt1EventObject;
ipt2Event.js
const ipt2EventObject = {
focus: (event) => {
console.log("ipt2的focus()方法执行了");
},
click: (event) => {
console.log("ipt2的click()方法执行了");
}
}
export default ipt2EventObject;
slt1Event.js
const focusEvent = (event) => {
console.log(event);
console.log("slt1的focus()方法执行了");
}
function click(event) {
console.log(event);
console.log("slt1的click()方法执行了");
}
const slt1EventObject = {
focus: focusEvent,
blur: (event) => {
console.log("slt1的blur()方法执行了");
},
click
}
export default slt1EventObject;
?目录结构
|