问题
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.
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.
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");
});
Thanks in advance for helping a jquery newb!
回答1:
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');
Protip: You can combine your class toggler: .toggleClass( "col-12 col-md-6")
来源:https://stackoverflow.com/questions/57379312/how-can-i-toggle-sibling-child-elements