核心思路:利用 事件委托 + 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>
网友评论