javascript - 一些相当于停止传播?
问题描述
我有一个问题...
我正在尝试使用以下方法获取元素 ID:
$('div').on('click',function(ev){
ev.stopPropagation();
checkEl = $(this).attr('id');
if(checkEl != 'topics' && checkEl != 'exfillVal' ){
$("#topics").hide();
}
})
但是...它还阻止具有不同事件侦听器的其他元素(单击一个)...我该如何实现呢?
$(function(){
var newHTML =[];
$('div').on('click',function(ev){
ev.stopPropagation();
checkEl = $(this).attr('id');
if(checkEl != 'topics' && checkEl != 'exfillVal' ){
$("#topics").hide();
newHTML.push('<span class="reopen" title="usuń">' + checkEl + '</span>');
}
$('#new').html(newHTML);
})
$('body').on('click', '.reopen',function(){
$(this).hide();
$("#topics").show();
})
// but that work
$('.reopen').on('click',function(){
$(this).hide();
$("#topics").show();
})
})
#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;
}
span{
padding:3px;}
<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 id="topics">SOME COOL DATA </div>
</div>
<div id="new"></div>;
正如您所看到的,当我单击 id 为“一、二、三、四、五、主要”的 div 时,一切正常...但是当单击附加跨度元素时...事件侦听器无法正常工作,因为附加单击时隐藏的元素被隐藏......而不是它只是创建另一个元素......我在哪里提出问题?
我可以用其他东西代替传播吗?
我如何重新排列代码?
任何帮助将不胜感激
解决方案
您可以通过比较来验证处理程序是在处理原始元素还是在处理父ev.target
元素ev.currentTarget
。当它们相同时,您就知道点击确实是在该元素上,并且您正在查看的不是父元素:
$('div').on('click',function(ev){
checkEl = $(this).attr('id');
if (ev.target === ev.currentTarget && checkEl != 'topics' && checkEl != 'exfillVal' ){
$("#topics").hide();
}
});
推荐阅读
- c# - 当主窗体关闭时,C# 杀死所有以 Application.Run 启动的进程
- php - 如何计算答案 a,b,c,d,e,f 被给出的次数?
- java - 如何使用第二个 ComputableFuture 对象设置 CompletableFuture 对象的字段值
- javascript - 从外部获取函数参数而不在 javascript 中执行此函数
- azure - Azure 添加您没有权限的应用注册
- scala - 如何使用 Either 产生所有错误(失败)
- javascript - 在 React 中处理多个输入
- c# - 为什么 Datetime.DayOfWeek 是错误的?
- angular - 选择器 NGRX 内的调度操作
- ruby - 当我运行 ruby 代码时,如何从带有表情符号的 document.txt 行中读取并在终端上显示它们?