JS怎么判断是哪个元素触发了点击事件?

我为多个div设置了点击事件, 我需要根据用户点击了哪个div,从而获取相应的数据显示给用户, 那么怎么判断用户点击了哪个div呢?

万千封印
浏览 6520回答 1
1回答

慕雪6442864

<!DOCTYPE html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <title>Title</title>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; .innerDiv{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; border:1px solid #cccccc;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width:500px;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height:50px&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style></head><body><div style="width:500px;height:500px;background-color: #1A68A2" id="container">&nbsp; &nbsp; <div class="innerDiv" data-index="1">1</div>&nbsp; &nbsp; <div class="innerDiv" data-index="2">2</div>&nbsp; &nbsp; <div class="innerDiv" data-index="3">3</div>&nbsp; &nbsp; <div class="innerDiv" data-index="4">4</div>&nbsp; &nbsp; <div class="innerDiv" data-index="5">5</div>&nbsp; &nbsp; <div class="innerDiv" data-index="6">6</div>&nbsp; &nbsp; <div class="innerDiv" data-index="7">7</div>&nbsp; &nbsp; <div class="innerDiv" data-index="8">8</div></div><script>&nbsp; &nbsp; function processInnderDiv(domDiv){&nbsp; &nbsp; &nbsp; &nbsp; console.log('div[data-index=%s] click',domDiv.getAttribute("data-index"));&nbsp; &nbsp; }&nbsp; &nbsp; document.getElementById("container").addEventListener("click",function(event){&nbsp; &nbsp; &nbsp; &nbsp; processInnderDiv(event.target);&nbsp; &nbsp; },false);</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript