【问题标题】:Bootstrap: maintaining active state based on routing when manually entering urlBootstrap:手动输入url时根据路由保持活动状态
【发布时间】:2017-08-18 18:32:22
【问题描述】:

这是一个运行良好的 plnkr 示例:http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview

一个带有 2 个链接的导航(路由到 2 个 ui-router 状态),以及一个在活动链接上维护活动类的 jQuery 方法。

index.html

<body ng-app='myApp'>
  <ul class="nav nav-pills">
    <li role="presentation" class="active"><a ui-sref="home">Home</a></li>
    <li role="presentation"><a ui-sref="news">News</a></li>
  </ul>
  <ui-view></ui-view>
</body>

app.js

angular.module('myApp', ['ui.router'])
    .config(function($stateProvider){
      $stateProvider.state('home', {
        url : '/home',
        template: '<h1>home</h1>'
      });
      $stateProvider.state('news', {
        url : '/news',
        template: '<h1>news</h1>'
      });

});

script.js

$(document).ready(function(){
  $(".nav a").on("click", function(){
    $(".nav").find(".active").removeClass("active");
    $(this).parent().addClass("active");
 });
});

该应用程序运行良好,除了尝试在浏览器导航器中手动输入网址时,例如,如果活动选项卡是 Home 并且我选择 http://localhost:8080/news/ 状态为 News,但活动类仍在 Home

【问题讨论】:

    标签: javascript jquery angularjs twitter-bootstrap angular-ui-router


    【解决方案1】:

    如果你直接访问 /news,你的函数永远不会被执行。它仅在单击导航链接时执行。您希望在初始加载以及状态更改时执行该函数。

    更好的方法是完全避免使用 jQuery 并以“Angular 方式”来做事。您可以为导航栏创建一个控制器,并在您的状态发生变化时在适当的元素上设置 active 类。

    【讨论】:

      【解决方案2】:

      当您直接浏览页面时,您的 onClick 函数不会执行。虽然你可以让它工作

      $(document).ready(function() {
          $PageName = window.location.href.split('/').pop();
          $PageName = $PageName.toLowerCase();
          $(".nav a").each(function() {
              $this = $(this);
              if($this.text().toLowerCase() == $PageName) {
                  $this.parent().addClass("active");
              }
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-09
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        相关资源
        最近更新 更多