简体   繁体   English

使用Java单击添加和删除类

[英]Adding and Removing Classes on click with Javascript

So in my rails app, I am trying to have it so that when when a user clicks a link in a menu, that link becomes underlined to indicate it is the current page. 因此,在我的Rails应用程序中,我尝试使用它,以便当用户单击菜单中的链接时,该链接带有下划线,以指示它是当前页面。 I have the basic set up down with javascript and css but I am having trouble getting the addClass() and removeClass() functions working. 我已经使用javascript和css进行了基本设置,但是我无法使addClass()removeClass()函数正常工作。

Right now, the active link underlines fine, however when the other link is clicked, the active class doesn't transfer (although the link seems to flicker). 现在, active链接下划线很好,但是,当单击另一个链接时,活动类不会传输(尽管该链接似乎闪烁)。 Any help would be much appreciated! 任何帮助将非常感激!

The Menu HTML 菜单HTML

<div id="collective_tabs">
  <ul>
    <li>
      <%= link_to 'Projects', collective_projects_path(@collective) %>
    </li>
    <li>
      <%= link_to 'Members', collective_members_path(@collective) class: 'active' %>
    </li>
  <ul>
</div>

CSS CSS

.active {
  border-bottom: 1px solid;
}

application.js 的application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require chosen-jquery
//= require messages
//= require bootstrap
//= require turbolinks
//= require_tree .

$(document).ready(function() {
    $('#collective_tabs li a').on('click', function(){
        $('li a.active').removeClass('active');
        $(this).addClass('active');
    });
});

Works perfectly here: 在这里完美工作:

http://jsfiddle.net/kez5zwgq/ http://jsfiddle.net/kez5zwgq/

Make sure you have your "a" tags defined in your HTML ;) 确保在HTML中定义了“ a”标签;)

HTML HTML

<div id="collective_tabs">
 <ul>
   <li>
    <a>potato</a>
   </li>
   <li>
    <a class="active">tomato</a>
   </li>
 <ul>
</div>

You might want to consider using the following CSS: 您可能要考虑使用以下CSS:

CSS CSS

.active {
   text-decoration: underline;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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