原生 JS 自动绑定多个事件
2019-10-01 本文已影响0人
前端技师胡帅博
核心思路:利用 事件委托 + data 属性
<div class="wrap">
<canvas id="id-canvas" data-action='draw_tile' width="600" height="500"></canvas>
<div class="inline-block">
<img src="imgs/b1.png" data-action='changeActiveTile' data-id="1">
<img src="imgs/b2.png" data-action='changeActiveTile' data-id="2">
<img src="imgs/b3.png" data-action='changeActiveTile' data-id="3">
<img src="imgs/b4.png" data-action='changeActiveTile' data-id="4">
</div>
<hr />
</div>
<script>
const actions = {
changeActiveTile(event) {
let id = Number(event.target.dataset.id);
window.activeTile = id
},
draw_tile(event) {
let id = Number(event.target.dataset.id);
window.activeTile = id
},
}
const bindEvents = () => {
e("body").addEventListener("click", event => {
let action = event.target.dataset.action;
actions[action] && actions[action](event );
});
};
const _main = () => {
bindEvents();
};
_main();
</script>