首页 > 解决方案 > 一些相当于停止传播?

问题描述

我有一个问题...

我正在尝试使用以下方法获取元素 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 时,一切正常...但是当单击附加跨度元素时...事件侦听器无法正常工作,因为附加单击时隐藏的元素被隐藏......而不是它只是创建另一个元素......我在哪里提出问题?

我可以用其他东西代替传播吗?

我如何重新排列代码?

任何帮助将不胜感激

标签: javascriptjquerystoppropagation

解决方案


您可以通过比较来验证处理程序是在处理原始元素还是在处理父ev.target元素ev.currentTarget。当它们相同时,您就知道点击确实是在该元素上,并且您正在查看的不是父元素:

$('div').on('click',function(ev){
     checkEl = $(this).attr('id');
     if (ev.target === ev.currentTarget && checkEl != 'topics' && checkEl != 'exfillVal' ){
         $("#topics").hide();
     }
});

推荐阅读