我为多个div设置了点击事件, 我需要根据用户点击了哪个div,从而获取相应的数据显示给用户, 那么怎么判断用户点击了哪个div呢?
--------------补充------------------
比如我用js写了个for循环造出10个div元素,然后添加给body。 然后我想为它们添加同一个点击事件, 点击事件里面想根据用户点击了不同的div,加载不同的数据。 我想知道这个点击事件要怎么写?
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.innerDiv{
border:1px solid #cccccc;
width:500px;
height:50px
}
</style>
</head>
<body>
<div style="width:500px;height:500px;background-color: #1A68A2" id="container">
<div class="innerDiv" data-index="1">1</div>
<div class="innerDiv" data-index="2">2</div>
<div class="innerDiv" data-index="3">3</div>
<div class="innerDiv" data-index="4">4</div>
<div class="innerDiv" data-index="5">5</div>
<div class="innerDiv" data-index="6">6</div>
<div class="innerDiv" data-index="7">7</div>
<div class="innerDiv" data-index="8">8</div>
</div>
<script>
function processInnderDiv(domDiv){
console.log('div[data-index=%s] click',domDiv.getAttribute("data-index"));
}
document.getElementById("container").addEventListener("click",function(event){
processInnderDiv(event.target);
},false);
</script>
</body>
</html>
假设创建了10个div:
<div class="xx" data-index="xxxx"></div>
$(document).on('click', '.xx', function (e) {
if($(e.target).attr('data-index') == 'xxxx'){
.....
}
})
如果这些div有父子级关系,这时就涉及到了事件代理,可以利用事件源e.target(ie 下是srcElement)的来获取当前点击的div。
如果没有父级关系,祖先关系,那就太好解决了。就在添加事件的函数里面加入你要处理的代码。
要是涉及到事件代理,具体还是找篇文章来看看吧。
window.event下面有个target
当前点击的就是this对象,不用去判断什么事件对象什么的,给每个div加个识别的属性,然后去根据需要去获取数据。
利用识别的属性,在通过函数的调用。
先贴出你的代码html和js。