javascript - 单击其中的任何内容时从父级中删除一个类

标签 javascript jquery modal-dialog

我找不到我要找的确切场景。 我正在尝试以替代关闭按钮的方式从父 div 中关闭一个类。为了给您一个清晰的思路,我发布了整个代码。

    $('.team__list li').on('click', function() {
        $('.team__list li').removeClass('active');
        $(this).addClass('active');
        console.log('hi');
    }); 

    $('.team__list li .close-button').click(function(event) {
        $(this).closest('.team__list li').removeClass('active');
        event.stopPropagation();
    });

    $('.active *').on('click',function(event) {
        console.log('hi');
        $(this).closest('.team__list li').removeClass('active');
        event.stopPropagation();
    });

第一个 block 在单击元素时触发事件类并将其从同级元素中删除,第二个 block 在关闭按钮时正确删除类。但是,我根本无法触发第三个方 block 。

应该注意(不确定是否重要)在接收到类 active 时,子元素(带有子元素本身)绝对定位在 active 元素之上。

编辑:

$('.team__list li').not('.active').on('click', function(event) {
        $('.team__list li').removeClass('active');
        $(this).addClass('active');
        console.log('open');
        event.stopPropagation();
    });



    $('.team__list li .close-button').click(function(event) {
        $(this).closest('.team__list li').removeClass('active');
        event.stopPropagation();
    });

    $(".team__list").on('click', ".active *", function(event) {
        console.log('close');
        $(this).closest('.team__list li').removeClass('active');
        event.stopPropagation();
    });

最佳答案

由于您在运行时添加和删除 class,因此您必须使用 event-delegation绑定(bind)你的事件。因为在页面加载期间注册的事件不适用于在运行时符合该事件条件的元素。

$(".team__list").on('click', ".active *", function(event) {
   //your code goes here.

关于javascript - 单击其中的任何内容时从父级中删除一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165245/

相关文章:

javascript - 在 HTML 编码中嵌入 Javascript 最佳实践

twitter-bootstrap - Bootstrap 模态百分比高度

Javascript:模块模式与构造函数/原型(prototype)模式?

javascript - 通过 PHP 提交 PDF 表单应返回哪些数据到 Adob​​e Reader?

jquery - 制作循环无限滚动

jquery - 无法读取 Angular 数据表中未定义的属性 'aDataSort'

javascript - 如何通过 Angular-Service 显示引导模式

html - CSS3模态背景不透明

Javascript计算器,如何在等于后保存显示值

javascript - 体素世界中的“剔除”