如何在单击链接时添加和删除类名

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

本文关键字:删除 添加 单击 链接      更新时间:2023-09-26

我想在我的rails应用程序中的表中切换2链接(send_emailemail_sent)的可见性。两个链接都在同一单元格内。

<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>

在我的css中有

.hidden{display: none;}

这是我的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 %>

您可以简单地使用jQuery中的removeClass()addClass()

Remove Class docs.

添加类文档

你做错了。$('.send_email > a')意味着您有send_email类到锚的父元素。$('a.send_email')是使用类选择锚的正确方法。

我会像这样使用hide(), show():

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