Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

javascript - I need to add and remove 2 different classes to different elements with one click.-jQuery

I want to add and remove a new class(Not toggle) in this span(footer-text)tag By clicking this div(footer-icon)tag. By jQuery or javascript. It needs to be work like siblings cause I have more span tag

For example-

<div class="footer-icon">Hello</div>

<span class="footer-text">Home</span>

Basically, I need to add and remove 2 different classes to different elements with one click. I need to click on this footer-icon class

Html-

  <svg version="1.1" class="footer-icon" viewBox="0 0 90 100" 
    xmlns="http://www.w3.org/2000/svg">
  </svg>
  <span class="footer-text">Home</span>

css-

.footer-icon-active{
    stroke: #fc494d;
}
.footer-active {
    color: #fc494d;
}

I have tried but it needs individual clicks

$(".footer-icon").click(function(event){
        $(".footer-icon").removeClass('footer-icon-active');
        $(this).addClass('footer-icon-active');
    });
    $(".footer-text").click(function(event){
        $(".footer-text").removeClass('footer-active');
        $(this).addClass('footer-active');
    });

enter image description here

question from:https://stackoverflow.com/questions/65889615/i-need-to-add-and-remove-2-different-classes-to-different-elements-with-one-clic

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So you have many .footer-icon and .footer-text pairs... And you want to set them as active on click of one of the other...

Try this:

// One click handler for both classes
$(".footer-icon, .footer-text").click(function(event){
  // Remove the two active classes everywhere
  $(".footer-icon").removeClass('footer-icon-active');
  $(".footer-text").removeClass('footer-active');
  
  // Depending which element was clicked
  // Add the active class to $(this)
  // and its corresponding prev or next sibling
  if($(this).is(".footer-icon")){
    $(this).addClass('footer-icon-active');
    $(this).next(".footer-text").addClass('footer-active')
  }else{
    $(this).prev(".footer-icon").addClass('footer-icon-active');
    $(this).addClass('footer-active')
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...