【问题标题】:Can't add a class to a list element and remove this same class from the other elements无法将类添加到列表元素并从其他元素中删除相同的类
【发布时间】:2016-01-24 14:52:46
【问题描述】:

所以我在运行 Ruby on Rails 的网站上使用网上找到的模板(其名称为“Easy Start”)。

主要困难是我有一个布局,其中包含“轻松启动”的导航栏及其页脚,并且页面内容保存在其他文件中。

我有麻烦的部分在这里:

<div id="divMenuRight" class="pull-right">
  <div class="navbar">
    <button type="button" class="btn btn-navbar-highlight btn-large btn-primary" data-toggle="collapse" data-target=".nav-collapse">
          NAVIGATION <span class="icon-chevron-down icon-white"></span>
    </button>
    <div class="nav-collapse collapse">
      <ul class="nav nav-pills ddmenu">
        <li class="dropdown active"> <%=link_to 'Accueil', '/'%></li>
        <li class="dropdown"> <%=link_to 'À Propos', '/about'%></li>
        <li class="dropdown"> <%=link_to 'Contact', '/contact'%></li>
      </ul>
    </div>
  </div>
</div>

如您所见,第一个 &lt;li&gt; 有 2 个类,称为“下拉”和“活动”。 "活动是使按钮变为红色并显示哪个页面处于活动状态的原因。

所以我尝试制作一个小的 jQuery 函数,在其中获取当前 URL 并尝试将“活动”类添加到正确的 &lt;li&gt;,同时根据我当前所在的页面从其他页面中删除它.

var url = $(location).attr('href')

if(url ==="http://localhost:3000/"){
    $("li.dropdown:nth-child(0)").addClass("active");
    $("li.dropdown").not(this).removeClass("active");

}
else if(url ==="http://localhost:3000/about"){
    $("li.dropdown:nth-child(1)").addClass("active");
    $("li.dropdown").not(this).removeClass("active");
}
else if(url ==="http://localhost:3000/contact"){
    $("li.dropdown:nth-child(2)").addClass("active");
    $("li.dropdown").not(this).removeClass("active");
}

但它不起作用,互联网上没有任何东西给我一个解决方案...... 我(有点)这样做是对的吗?或者我该怎么做?

提前谢谢你

【问题讨论】:

  • 您的浏览器控制台是否报告了任何错误(大多数浏览器为 F12)?
  • 概念有效。代码是否在 document.ready 处理程序中?您是否测试过条件以查看它们是否匹配?也可以使用location.pathname 访问更少的 url .. 将其粘贴到浏览器控制台中会看到它从 url 中删除协议和域
  • 第三次检查应该是url ==="http://localhost:3000/contact" 如果location 指的是window.location,这看起来是错误的var url = $(location).attr('href')。应该是var url = location.href。现在你如何调试你的代码?似乎很容易检查至少url 在您的代码中的样子。不管怎样,看看下面彼得的回答
  • :nth-child 选择器索引开始于1 "要匹配的每个子元素的索引,从1开始" api.jquery.com/nth-child-selector
  • David Thomas > 有一个错误,但有一个库甚至不使用,我很快就会删除,与这个案例无关 charlietfl > 是的,谢谢,它更简单! A. Wolff > 是的,应该是“/contact”,我想我的复制/粘贴失败了。我会在发表此评论后编辑我的问题。尽管如此,当我执行console.log((location).attr('href'))时,我得到了我当前的url,当我点击我的链接时它被修改了……guest271314>是的,你是对的,一开始我以为是数组!

标签: jquery html class ruby-on-rails-4


【解决方案1】:

这里为什么要通过javascript来实现你的目标?

我会简单地做这样的事情:

<li class="dropdown <%= "active" if controller.controller_name == "contact" %>">
  <%= link_to 'Contact', '/contact'%>
</li>

你可以通过实现一个辅助方法让它更漂亮。

【讨论】:

【解决方案2】:

我可以为您提供一种替代方法来实现您想要的结果,使用 DOM 或 jQuery,但是如果没有深入了解报告的错误(如果有的话),很难说为什么它没有按书面方式工作(尽管它可能是就像 URL 中存在或不存在的尾部斜杠一样简单)。

还值得注意的是Peter de Ridder's answer,在 Ruby 中实现该解决方案几乎可能更容易且更明智。

使用 jQuery,我建议的替代方法是:

// retrieving the current URL of the page:
var currentURL = document.location.href,

    // selecting the <li> elements with the
    // 'dropdown' and 'active' classes,
    // removing the 'active' class from those elements:
    $('li.dropdown.active').removeClass('active');

    // selecting all <a> elements within the <li>
    // elements of class 'dropdown', and filtering
    // those elements:
    activeLinks = $('li.dropdown a').filter(function () {

        // retaining only those elements
        // whose href property (absolute URL)
        // matches the current page's URL:
        return this.href === currentURL;

    // finding the closest ancestor <li> element
    // with the 'dropdown' class, and adding the
    // 'active' class-name to those elements:
    }).closest('li.dropdown').addClass('active');

使用 DOM:

// retrieving the URL of the current page:
var currentURL = document.location.href,

// finding all <a> elements within the <li>
// elements with the class of 'dropdown',
// and using Array.from() to convert that
// collection into an Array:
    links = Array.from( document.querySelectorAll('li.dropdown a') );

// creating an Array from the collection
// returned by document.querySelectorAll(),
// iterating over that Array with
// Array.prototype.forEach():
Array.from( document.querySelectorAll('li.dropdown') ).forEach(function (li) {
    // the first argument (here: 'li') is
    // the array element of the Array over
    // which we're iterating.

    // here we remove the 'active' class
    // from those <li> elements:
    li.classList.remove('active');
});

// here we filter the Array of links:
links.filter(function (a) {

    // retaining only those whose
    // href property contains the
    // (absolute) URL matching the
    // URL of the current page:
    return a.href === currentURL;

// iterating over the Array returned
// Array.prototype.filter(), using
// Array.prototype.forEach():
}).forEach(function (a) {

    // finding the closest ancestor <li>
    // element, with the class of 'dropdown,'
    // to the current <a> element, and
    // adding the 'active' class-name:
    a.closest('li.dropdown').classList.add('active');
});

或者,使用 DOM,但使用箭头函数 (ECMAScript 6);下面的方法做同样的事情,但使用箭头函数来避免使用更详细的匿名函数:

var currentURL = document.location.href,
    links = Array.from( document.querySelectorAll('a') );

Array.from( document.querySelectorAll('li.dropdown') ).forEach(function (li) {
    li.classList.remove('active');
});

links.filter( a => a.href === currentURL )
     .forEach( a => a.closest('li.dropdown').classList.add('active'));

【讨论】:

  • 工作得很好,非常感谢,有一天我可以用 Ruby 做到这一点,但遗憾的是今天不是今天,所以我会采纳你的解决方案并再次感谢你很多!
  • 我更新了我的答案,您使用 Javascript 使您的代码复杂化。
  • @Peter,如果您的评论是针对我的,您会注意到我在第二段中的建议是使用您的答案?不幸的是,除此之外,我能提供的唯一建议是 JavaScript 解决方案,因为我还不熟悉 Ruby。至于你的回答,我强烈建议,在这种情况下,要求你评论你的代码以解释它在做什么,以及它是如何工作的;这样我和其他像我一样的人可能会学习更好的方法和技术,希望在这个过程中开始学习 Ruby。
  • 我知道,我的评论是针对 Jaeger 的,因为如果他在不需要时使用更复杂的方法是很不幸的。通常我会添加更多解释,但这行代码对我来说似乎是不言自明的。
猜你喜欢
  • 1970-01-01
  • 2020-09-30
  • 2017-12-20
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
相关资源
最近更新 更多