首页 > 解决方案 > 如何找到点击元素的id

问题描述

我的代码:

$('div').on('click',function(){
    checkEl = $(this).attr('id');
    console.log(checkEl);
});

因此,每次单击 div 时,它都会抛出一个被单击元素的 id ...

但是.. 在console.log 上,我得到了 3/4/5/6 个元素,这取决于我选择的位置...

我的输出是预期 div 的 id,但也显示父 div...

如何获取精确点击元素的 id?

$(function(){
$('div').on('click',function(){
    checkEl = $(this).attr('id');
    console.log(checkEl);
    })
    })
#main{
position:relative;
width:300px;
background-color:red;
}
div{
position:relative;
border:1px solid gray;
padding:15px;
width:100%:
}
#one{
background-color:black;
}
#two{
background-color:blue;
}#three{
background-color:orange;
}#four{
background-color:yellow;
}#fifth{
background-color:purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="one">
<div id="three">
<div id="four">
<div id="fifth">
</div>
</div>
</div>
</div>
</div>

标签: jquery

解决方案


为避免父元素也触发该事件,请添加对stopPropagation的调用:

$('div').on('click',function(e) {  // <-- argument
    checkEl = $(this).attr('id');
    console.log(checkEl);
    e.stopPropagation(); // <---
});

推荐阅读