[英]jQuery: Toggle class on one element, remove same from all other
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. 因此:单击某些.zoom分类元素,将其父级切换为最大化,并且for循环检查与父级相同的所有其他元素,并删除.maximized类。 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. 使用for循环和removeClass构造脚本的原因是,相同的.zoom元素能够最小化其父元素,而不仅仅是最大化它们。
Im not a javascript professional, but to my knowledge this should work in principle. 我不是一名JavaScript专业人士,但据我所知,这原则上应该可行。 Am I missing anything here? 我在这里想念什么吗?
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. 您可以在此处找到一支笔,以查看正在使用的脚本。
$(".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');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.