我想在手风琴里面造个手风琴.我还有点挣扎。
本质上,我有一个div .applicant,单击它会添加一个类.expand,它将高度设置为auto,但是在.applicant div中,我有另一个div .applicant-child,它应该做同样的事情,并且做.但是,当您单击.applicant时,.applicant-child会关闭,这意味着您必须再次单击.applicant来打开嵌套元素的视图。
这是我的代码:
<div class="row">
<div class="col-sm-12">
<div class="applicant">
<p><b>PS4 Tournaments</b></p>
<div class="applicant-child">
<p>lalal</p>
<p>lalal</p>
</div>
</div>
</div>
</div>jQuery
$('.applicant').click(function(){
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});
$('.applicant-child').click(function(){
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});我可以简单地将$(this).removeClass('expand');从.appliant中删除,但我们将显示大量数据,因此这并不理想。
我该怎么解决这个问题?
(预先谢谢:)
发布于 2018-08-09 15:24:57
这只是一件引发人们期待的行为的事件。请参阅链接 on jQuery关于如何禁用click-Event以使DOM冒泡并触发父元素上的事件。
基本上,你只需要这样做:
$('.applicant-child').click(function(event){
event.stopPropagation();
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});发布于 2018-08-09 15:24:14
你想防止冒泡。冒泡意味着,您所响应的事件正将DOM传递到父对象,直到它到达窗口。
请查看"event.stopPropagation()“方法,该方法将阻止任何后续侦听器作出反应。
发布于 2018-08-09 15:27:53
在单击处理程序上,如果您通过param:
$('.applicant').click(function(event){
console.log(event.target);
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});您可以使用event.target来检查您是要单击父级还是子级,并决定从那里采取什么操作。
https://stackoverflow.com/questions/51770701
复制相似问题