jquery - 如何找到点击元素的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>
解决方案
为避免父元素也触发该事件,请添加对stopPropagation的调用:
$('div').on('click',function(e) { // <-- argument
checkEl = $(this).attr('id');
console.log(checkEl);
e.stopPropagation(); // <---
});
推荐阅读
- javascript - 在 vue.js 中创建一个包含数据的 obj 名称
- javascript - 为什么这种将 html 表单信息下载为字符串/.txt 文件的方法会从文件中删除所有换行符?
- python-3.x - 结束 LTSpice 模拟的指令
- tableau-api - 如何修复在订单中检查日期的计算字段?
- android-textinputlayout - 有没有办法在 1.1.0+ 中使用 TextInputLayout 创建未填充的 TextInputEditText?
- codeigniter - 如何从codeigniter的同一控制器中的2个相关表中获取数据?
- docker - Docker 安装在 armv7 上
- c# - C# SignalR2 从服务器接收在线用户列表
- math - 使用全局旋转在其局部轴上旋转对象?
- excel - 插入 Chr(149) 来分隔段落?