gpt4 book ai didi

javascript - 一些相当于停止传播?

转载 作者:行者123 更新时间:2023-12-03 00:16:19 25 4
gpt4 key购买 nike

我有一个问题...

我正在尝试使用以下方式获取元素 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.targetev.currentTarget 进行比较来验证处理程序是否正在处理原始元素或父元素。当它们相同时,您就知道点击确实发生在该元素上,并且它不是您正在查看的父元素:

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

关于javascript - 一些相当于停止传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com