简体   繁体   中英

How to add and remove a class name from a link when clicked?

I want to toggle the visibility of 2 links ( send_email and email_sent ) in a table in my rails app. Both links are within the same cell.

<table >
<% @applications.each do |application| %>
 <tr>
  <td>
   <a href="mailto:grant@example.com" class="send_email">Invite for an interview</a>

   <a href="" class="email_sent hidden">Undo</a>
  </td>
 </tr>
<% end %>
</table>

In my css I have

.hidden{display: none;}

Here is my javascript

<%= javascript_tag do %>
 $(function(){
  $('.send_email > a').click(function(){
   // add the hidden class to send_email
   // remove the hidden class from the next email_sent link
  });
  $('.email_sent > a').click(function(){
   // add the hidden class to email_sent
   // remove the hidden class from the previous sent_email link
  });
 });
<% end %>

You can simply use the removeClass() and addClass() from jQuery.

Remove Class docs.

Add Class docs.

You are doing it wrong. $('.send_email > a') means you have send_email class to the parent element of the anchor. $('a.send_email') is the right way to select the anchor with the class.

I would use hide() , show() like this:

$('a.send_email').click(function(){
  $(this).hide();
  $('.email_sent').show();
});

$('a.email_sent').click(function(){
  $(this).hide();
  $('.send_email').show();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM