jQuery:在一个元素上切换类,从其他元素中删除相同的元素

时间:2022-08-27 12:32:47

new here and deeply hoping I'm not missing a stupid syntax flaw. I was thinking that my problem is a fairly common one, but somehow nothing has helped so far in my specific case. There is a simple inline-block list of Image Galleries which are zoomable to fill the parent width. As soon as one is zoomed through click on a child, the others should unzoom by stripping of the class which maximizes them. Nothing more to it. I achieved the first part via the following jQuery (where the problem is hidden in the for-loop, I think):

新来的,并且深深地希望我不会错过一个愚蠢的语法缺陷。我认为我的问题是一个相当普遍的问题,但到目前为止,在我的具体案例中,没有任何帮助。有一个简单的图像库嵌入式阻止列表,可以缩放以填充父级宽度。一旦通过点击一个孩子进行缩放,其他人应该通过剥离最大化它们的类来解除缩放。没有更多的东西。我通过以下jQuery实现了第一部分(我认为问题隐藏在for循环中):

  $(".zoom").click(function() {
    var target = $(this);
    target.closest('div.product-item').toggleClass('maximized');

    var ot = document.getElementsByClassName('product-item');
    for (var i = 0; i < ot.length; i++) {
      if (ot[i] !== target) {
        ot[i].removeClass('maximized');
      }
    }
  });

So: Some .zoom classed element is clicked, its parent is toggled to maximize and a for loop checks all other elements of the same class as the parent and removes the .maximized class. The reason the script is constructed with a for-loop and a removeClass is so that the same .zoom elements are able to minimize their parent elements, not only to maximize them.

因此:单击一些.zoom分类元素,将其父级切换为最大化,并且for循环检查与父级相同的所有其他元素,并删除.maximized类。使用for循环和removeClass构造脚本的原因是,相同的.zoom元素能够最小化其父元素,而不仅仅是最大化它们。

Im not a javascript professional, but to my knowledge this should work in principle. Am I missing anything here?

我不是一个javascript专业人士,但据我所知,这应该是原则上的工作。我在这里错过了什么吗?

This post from a year ago addressed a similar problem but didn't help in my case: jQuery onClick: How to add class to element and remove from all others

一年前的这篇文章解决了类似的问题但在我的案例中没有帮助:jQuery onClick:如何向元素添加类并从其他所有元素中删除

You can find a pen to see the script in action here.

您可以在这里找到一支笔来查看脚本。

1 个解决方案

#1


$(".zoom").on('click',function() {
    var target = $(this);
    $('div.product-item').removeClass('maximized');
    target.closest('div.product-item').toggleClass('maximized');
});

you can use

您可以使用

if(target.closest('div.product-item').hasClass('maximized')){
      $('div.product-item').removeClass('maximized');
  }else{
      $('div.product-item').removeClass('maximized');
          target.closest('div.product-item').addClass('maximized');
  }

JSFIDDLE

#1


$(".zoom").on('click',function() {
    var target = $(this);
    $('div.product-item').removeClass('maximized');
    target.closest('div.product-item').toggleClass('maximized');
});

you can use

您可以使用

if(target.closest('div.product-item').hasClass('maximized')){
      $('div.product-item').removeClass('maximized');
  }else{
      $('div.product-item').removeClass('maximized');
          target.closest('div.product-item').addClass('maximized');
  }

JSFIDDLE