如何使用搜索栏过滤我的bootstrap 4导航栏链接?

时间:2017-04-30 04:05:25

标签: javascript jquery twitter-bootstrap search filtering

我正在使用Bootstrap 4过渡我的旧网站,所以它绝对是一个学习过程。

我的网站布局工作正常,但我发现我的左侧垂直导航栏有很多链接。其中许多分组在倒塌的巢穴中。

我认为在我的导航栏顶部添加搜索栏会很好,这样我就可以根据在搜索栏中输入的部分字符串来过滤链接。这适用于未隐藏在隐藏div(或class=collapsed boostrap 4 ul)内的链接。

我非常感谢您协助修改我的代码,以显示包含隐藏在折叠的ul内的所有链接的过滤结果?

Here's a fiddle



$('.search-filter').on('keyup', function() {
  var input = $('.search-filter').val();
  var filter = input.toLowerCase();

  if (filter.length == 0) { // show all if filter is empty
    $('a').each(function() {
      $(this).show(); // show links
    });
    return;
  } else {
    $('a').removeClass('collapsed');
    $('a').each(function() {
      $(this).hide(); // hide all links once search is begun
    });

    $('a:contains("' + filter + '")').each(function() {
      $(this).removeClass('collapsed'); // remove bootstrap 4 collapsed class designation
      $(this).show(); // show only matched links to search string?

    });
  }
});

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');

.navbar-nav.sidebar-nav {
  position: absolute;
  left: 0;
  top: 0;
  margin-top: 56px;
  padding-bottom: 56px;
  height: 100vh;
  background: #292b2c;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  overflow: auto;
}

.navbar-brand {
  display: inline-block;
  padding-top: .25rem;
  padding-bottom: .25rem;
  margin-right: 1rem;
  font-size: 1.25rem;
  line-height: inherit;
  white-space: nowrap;
  color: #fff;
}

.navbar-nav .nav-link {
  color: rgba(255, 255, 255, .5);
}

<div id="link-content">
  <ul class="sidebar-nav navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#"><i class="fa fa-fw fa-home"></i> Home</a>
    </li>
    <li class="nav-item">
      <label for="nav-search" class="col-2 col-form-label sr-only">Search links</label>
      <div class="col p-2">
        <input class="form-control form-control-sm search-filter" type="search" id="nav-search" placeholder="Search for tools">
      </div>
    </li>
    <li class="nav-item">
      <span class="navbar-brand">Popular tools</span>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#"><i class="fa fa-fw fa-calculator"></i> Calculator</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#"><i class="fa fa-fw fa-battery-3"></i> Battery </a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#"><i class="fa fa-fw fa-database"></i> Pancake Batter</a>
    </li>

    <li class="nav-item">
      <a class="nav-link" href="#"><i class="fa fa-fw fa-clock-o"></i> Marzipan</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#"><i class="fa fa-fw fa-tags"></i> Cakes and Muffins</a>
    </li>
    <li class="nav-item">
      <span class="navbar-brand">Categories</span>
    </li>
    <li class="nav-item">
      <a class="nav-link nav-link-collapse collapsed" data-toggle="collapse" href="#collapseComponents"><i class="fa fa-fw fa-flask"></i> Cars</a>
      <ul class="sidebar-second-level collapse" id="collapseComponents">
        <li>
          <a class="nav-link-collapse collapsed" data-toggle="collapse" href="#collapseMulti2">American</a>
          <ul class="sidebar-third-level collapse" id="collapseMulti2">
            <li>
              <a href="#">Ford</a>
            </li>
            <li>
              <a href="#">GMC</a>
            </li>
          </ul>
        </li>
        <li>
          <a class="nav-link-collapse collapsed" data-toggle="collapse" href="#collapseMulti3">European</a>
          <ul class="sidebar-third-level collapse" id="collapseMulti3">
            <li>
              <a href="#">BMW</a>
            </li>
            <li>
              <a href="#">Audi</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:8)

好吧,我想我已经自己想出来了(在这篇文章的帮助下,对一个不区分大小写的filter)。

1)我通过将链接包装在div with id #link-content中来更新链接,以将我的过滤器与主页和搜索输入分开。

2)我添加了上面引用的不区分大小写的方法

我的HTML:

   <ul class="sidebar-nav navbar-nav">
      <li class="nav-item active">
         <a class="nav-link" href="#"><i class="fa fa-fw fa-home"></i> Home</a>
      </li>
      <li class="nav-item">
         <label for="nav-search" class="col-2 col-form-label sr-only">Search links</label>
         <div class="col p-2">
            <input class="form-control form-control-sm search-filter" type="search" id="nav-search" placeholder="Search for tools">
         </div>
      </li>
 <div id="link-content"><!-- added this to wrap the links-->     
      <li class="nav-item">
         <span class="navbar-brand">Popular tools</span>
      </li>
      <li class="nav-item filter">
         <a class="nav-link" href="#"><i class="fa fa-fw fa-calculator"></i> Calculator</a>
      </li>
      <li class="nav-item  filter">
         <a class="nav-link" href="#"><i class="fa fa-fw fa-battery-3"></i> Battery </a>
      </li>
      <li class="nav-item  filter">
         <a class="nav-link" href="#"><i class="fa fa-fw fa-database"></i> Pancake Batter</a>
      </li>

      <li class="nav-item  filter">
         <a class="nav-link" href="#"><i class="fa fa-fw fa-clock-o"></i> Marzipan</a>
      </li>
      <li class="nav-item  filter">
         <a class="nav-link" href="#"><i class="fa fa-fw fa-tags"></i> Cakes and Muffins</a>
      </li>
      <li class="nav-item  filter">
         <span class="navbar-brand">Categories</span>
      </li>
      <li class="nav-item ">
         <a class="nav-link nav-link-collapse collapsed" data-toggle="collapse" href="#collapseComponents"><i class="fa fa-fw fa-flask"></i> Cars</a>
         <ul class="sidebar-second-level collapse" id="collapseComponents">
            <li>
               <a class="nav-link-collapse collapsed" data-toggle="collapse" href="#collapseMulti2">American</a>
               <ul class="sidebar-third-level collapse" id="collapseMulti2">
                  <li>
                     <a href="#">Ford</a>
                  </li>
                  <li>
                     <a href="#">GMC</a>
                  </li>
               </ul>
            </li>
            <li>
               <a class="nav-link-collapse collapsed" data-toggle="collapse" href="#collapseMulti3">European</a>
               <ul class="sidebar-third-level collapse" id="collapseMulti3">
                  <li>
                     <a href="#">BMW</a>
                  </li>
                  <li>
                     <a href="#">Audi</a>
                  </li>
               </ul>
            </li>
         </ul>
      </li>
      </div>
   </ul>

我的更新代码:

// Case insensitive method for filter
jQuery.expr[':'].casecontains = (a, b, c) => jQuery(a).text().toUpperCase().indexOf(c[3].toUpperCase()) >= 0;

$('.search-filter').on('keyup', function () {
            var input = $('.search-filter').val();
                        console.log('input: '+input);
            if (input.length != 0) { 
            // first hide the div #link-content lists from view
            $('#link-content li').hide();
            // but secretly unhide the collapsed links
            // using .show, so the nested uls can be viewed
            $('#link-content li.nav-item ul').show();
            // then filter in the matching links only
            $('#link-content li:casecontains("'+input+'")').show();
            } else {
            // secretly unhide the collapsed links
            $('#link-content li.nav-item ul').hide();  
            // if search is empty, show the div and reset columns
            $('#link-content li').show();
            }
        });

这是一个fiddle,其中包含打开任何隐藏链接的工作示例(在boost 4中折叠了类)。

答案 1 :(得分:7)

我使用的方法是记住哪些项匹配,然后使用该列表取消隐藏父母。

更新小提琴:https://jsfiddle.net/j2gpann3/1/

这种方法的优势在于,隐藏的子菜单项(如&#39; BMW&#39;等)现在将出现在搜索中,并且不会在其他项目之上留下巨大的空白隐藏的物品。正则表达式搜索会搜索每个单词的出现次数,因此即使它们与菜单项文本无关,它仍然会匹配。

$('.search-filter').on('keyup', function() {
  var matches = [];
  var input = $.trim($('.search-filter').val());
  var val = '^(?=.*\\b' + input.split(/\s+/).join('\\b)(?=.*\\b') + ').*$'; // using individual word matching filter from http://stackoverflow.com/a/9127872/1544886
  var filter = RegExp(val, 'i');

  if (input.length === 0) { // show all if filter is empty

    $('.collapse').removeClass('show').addClass('collapsed'); // hide collapsable items fast.
    $('.hide').removeClass('hide'); // remove any hidden elements from previous searches
  } else {
    $('.collapse').addClass('show'); // show all collapsed items

    $('ul.sidebar-nav a:not(".home")').filter(function() { // skip home <li> so it shows permanently
        $this = $(this);

        // test for a match to search string
        text = $this.text().replace(/\s+/g, ' ');
        var isMatch = filter.test(text);

                // store match so we can unhide parents of this item 
        if (isMatch) matches.push($this);

        return !isMatch;
    }).parent().addClass('hide'); // this hides any <li> that doesn't match search terms. Hiding <a> results in large gaps in the output

    $.each(matches, function() { // unhide parents of our matches
        this.parentsUntil(".sidebar-nav", ".hide").removeClass('hide');
    });
  }
});

该演示需要在Home链接中添加home类,以防止它被搜索隐藏:

<a class="nav-link home" href="#"><i class="fa fa-fw fa-home"></i> Home</a>

添加了hide的CSS类:

.hide {
  display: none;
}

答案 2 :(得分:1)

如果删除:

toLowerCase();

如果您完美输入,一切都完美匹配。问题是您将搜索字词设为小写,但它与小写字词不匹配。因此,当您键入计算器时,它不匹配,因为实际导航项显示为计算器,具有大写c。

因此,您也可以通过HTML或JavaScript将导航项设置为小写,或者以不同的方式进行操作,即使用ID,但如果网站是动态的,则会导致问题。

一些奇怪的工作可能是将每个单词的首字母大写,以便它实际上与HTML匹配。看看How to capitalize first letter of each word, like a 2-word city?