通过 jQuery 添加类后,jQuery 不删除类

发布于 2024-12-27 03:55:26 字数 678 浏览 3 评论 0原文

今天早上我似乎在 removeClass 方面遇到了一些麻烦。首先,我单击一个 div 添加类 'containerhover',然后当我单击关闭按钮时,它不会删除刚刚添加到 div 的类

我不知道这是否与仅添加到 dom 而没有实际编码到 HTML 中有关。请有人帮忙。

HTML

<div class="container"></div>

jQuery

$(function() {

    $('.container').click(function(e) {
        var mythis = $(this);
        mythis.addClass("containerhover");
        mythis.find('.backface').addClass("bfhover");
        mythis.find('.album').addClass("ahover");
    });

    $('.closealbum').click(function(e) {
        $('.container').removeClass('containerhover');
    });
});

I seem to have run into a bit of trouble this morning with removeClass. First I click a div to add Class 'containerhover', then when I click the close button it will not remove the class that it has just added to the div.

I don't know if this has something to do with it being added to the dom only and not being actually coded into the HTML. Please can someone help.

HTML

<div class="container"></div>

jQuery

$(function() {

    $('.container').click(function(e) {
        var mythis = $(this);
        mythis.addClass("containerhover");
        mythis.find('.backface').addClass("bfhover");
        mythis.find('.album').addClass("ahover");
    });

    $('.closealbum').click(function(e) {
        $('.container').removeClass('containerhover');
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宫墨修音 2025-01-03 03:55:26

使用 .on() 将事件附加到容器,然后仅当单击 .closealbum 元素时才激活它。另外,添加 event.stopPropagation() 方法以防止事件进一步冒泡:

$('.container').on('click', '.closealbum', function(e) {
    $('.container').removeClass('containerhover');
    e.stopPropagation();
});
  1. 您的问题是由于绑定时 .closealbum 元素不存在而引起的。 点击事件。
  2. 您的元素位于另一个元素内部。如果没有e.stopPropagation(),事件会冒泡,第一个事件也会被触发,撤消第二个事件的removeClass。

演示:http://jsfiddle.net/knCR8/1/

Use .on(), to attach the event to the container, and activate it only if the .closealbum element is clicked. Also, add the event.stopPropagation() method to prevent the event from bubbling further:

$('.container').on('click', '.closealbum', function(e) {
    $('.container').removeClass('containerhover');
    e.stopPropagation();
});
  1. Your problem is caused by the fact that the .closealbum element does not exist when binding the click event.
  2. Your element is positioned inside the other element. Without e.stopPropagation(), the event bubbles up, and the first event will also be triggered, undoing the second event's removeClass.

Demo: http://jsfiddle.net/knCR8/1/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文