如何切换同级子元素? [英] How can I toggle sibling child elements?
问题描述
我希望能够单击一个项目并切换其类别.这正在按预期方式工作.同样,当单击该项目时,子元素的类也会切换(以便使用CSS隐藏).一切正常.
I want to be able to click an item and toggle its classes. This is working as expected. Also, when the item is clicked a child element's class toggles (in order to hide with CSS). This is working as expected.
我想单击这些项目之一的任何同级,并切换其他项目的类.这正在按预期方式工作.这是我遇到的问题:我希望能够单击一个项目并具有同级的子元素的类切换-这无法按我希望的那样工作.
I want to click any sibling to one of these items and have the others' classes toggle. This is working as expected. Here is where I am stuck: I want to be able to click an item and have the sibling's child element's class toggle - this is NOT working as I had hoped.
我已经使用了一些帮助文章来使用jquery达到这一目标,但是我的newb知识并不能帮助我解决所有问题.
I've used some help articles to get this far using jquery, but my newb knowledge isn't getting me all of the way there.
此Codepen具有我尝试清除的HTML和JS: https://codepen. io/deejmer/pen/zgRYyj
This codepen has the HTML and JS that I'm trying flush out: https://codepen.io/deejmer/pen/zgRYyj
$(".feature-expand a.card").click(function(e){
e.preventDefault();
$(this).parent().toggleClass( "col-12").toggleClass( "col-md-6");
$(this).parent().siblings().removeClass( "col-12").addClass("col-md-6");
$(this).find(".hidden-item").toggleClass( "shown");
});
预先感谢您对jquery newb的帮助!
Thanks in advance for helping a jquery newb!
推荐答案
只是所有个隐藏元素,除了这一个.
Just all hidden elements except this one.
let thisHiddenItem = $(this).find(".hidden-item");
$('.hidden-item').not(thisHiddenItem).removeClass('shown');
thisHiddenItem.toggleClass("shown");
Demo
如有必要,通过定位包含的要素元素来限制范围:
If necessary, limit scope by targeting the containing feature element:
$(this).closest('.some-wrapper-el').find('.hidden-item').removeClass('shown');
提示:您可以组合使用类别切换器:.toggleClass( "col-12 col-md-6")
Protip: You can combine your class toggler: .toggleClass( "col-12 col-md-6")
这篇关于如何切换同级子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!