click - 单击绝对位置而不是后面的元素
问题描述
我有一个卡片列表,以及两个绝对定位的按钮。
我有一个带有两个按钮的元素,我的垃圾桶图标上有一个 JS 事件。
CSS
.list > .choice {
position: relative;
margin: 5px 0;
padding: 15px;
cursor: pointer;
background: rgb(254, 254, 254);
border-radius: 7px;
border: 1px solid rgb(229, 229, 229);
transition: 0.3s;
}
.list > .choice:hover {
background: rgb(245, 247, 248);
}
.list > .choice > .choice_badge {
display: inline-block;
vertical-align: baseline;
width: 100px;
height: 25px;
margin-right: 10px;
border-radius: 5px;
border: 1px solid black;
text-align: center;
}
.list > .choice > .choice_content {
display: inline-block;
vertical-align: middle;
}
.list > .choice > .choice_content > .choice_title {
font-weight: bold;
}
.list > .choice > .choice_content > .choice_sub_title {
font-size: 1.2rem;
}
.list > .choice > .choice_options {
position: absolute;
top: 50%;
right: 15px;
transform: translateY(-50%);
color: rgb(116 117 118);
}
.list > .choice > .choice_options > .material-icons {
margin-left: 1.2rem;
color: black;
font-size: 2rem;
}
.list > .choice > .choice_options > .material-icons > a {
color: black;
text-decoration: none;
}
HTML
<div class="list">
<div class="character choice" user_id="0">
<div class="choice_content">
<span class="choice_title">Lorem IPSUM</span>
<br/>
<span class="choice_sub_title">Lorem IPSUM</span>
</div>
<div class="choice_options">
<span class="material-icons"><a href="#">create</a></span>
<span class="material-icons delete">delete</span>
</div>
</div>
</div>
JS (jQuery)
$(document).ready(function(){
$(document).on('click', '.choice', function(){
alert('clicked on "choice" element');
});
$(document).on('click', '.delete', function () {
alert('clicked on delete button');
});
});
当我单击垃圾箱时,会打开一个弹出窗口,但是因为后面有 .choice 事件,所以弹出窗口打开并且导航器将页面更改为 mylink。
有人知道如何解决这个问题吗?谢谢。
解决方案
我可以看到删除图标按钮位于 .choice 元素中。正如您所知,单击事件会影响元素及其子节点,因为如果单击元素或子节点,则会触发该事件。但是,从我的角度来看,修复很容易,您不需要t 需要两个事件。
$(document).ready(function(){
$(document).on('click', '.choice', function(e){
// check if clicked element is the delete button
if($(e.target).hasClass('delete')){
// code for delete event
//--you could provide a method here to make this cleaner
delete(e.target);
} else {
// code for choice element
choice(e.target);
}
});
});
function delete(args){
// code here
}
为 .choice 元素及其子元素(.delete 元素)设置单独的事件是相当不必要的。至少我是这么认为的
推荐阅读
- webpack - 入口点的 webpack vue-loader 问题:“块中的错误”
- c# - 无法将 baseprice 输出到小计
- python - 如何获取决策树中的所有基尼指数?
- c++ - 将第一个元素移动到 forward_list 的末尾
- css - 如何在 twitter bootstrap 4 中显示一个可折叠项目?
- git - 同一主机上的多个git账户git
- android - 循环数据是不对的
- mysql - Mysql - 如果整个相同的行已经存在,则在插入新行时忽略警告
- haskell - 如何在 Stack 中找到包的名称?
- php - PHP MySQL:从一列获取数据,但使用单独表中不同列的id