根据搜索值显示/隐藏列表项

时间:2016-11-30 22:42:52

标签: javascript jquery

我有以下列表通过AJAX引入,每个'li'都有一个默认的'display:none'值(列表有800'li'所以我在这里切割它只显示3个):

基本上我需要当有人在搜索字段中键入一个值来浏览整个列表时将该值与'h3>进行比较每个列表中都有一个文本,所以如果它在'h3>里面,可以说有人输入“佛罗里达”。 a'显示它,其余的隐藏它。

当有人将搜索值更改为“加利福尼亚”时,它应该再次遍历所有列表,隐藏实际的列表(在本例中为“Florida”)并显示其h3中具有“California”文本的那些>一个。

谢谢!

<form method="post" action="/employers/">
    <fieldset>
        <legend>Employer search</legend>
        <div class="field">
            <label for="searchtext" class="hidden">Search employers</label>
            <div class="clear-input js-clear-input">
                <input id="searchtext" type="text" name="RecruiterName" value="Florida" placeholder="Start typing…" class="clear-input__input js-recruiter-lookup js-clear-input-input" autocomplete="off">
                    <i data-icon="x" class="clear-input__trigger icon-before js-clear-input-trigger" style="display: inline;"></i>
                </div>
            </div>
            <div class="field">
                <select name="RecruiterTypeId" class="js-recruiter-type">
                    <option value="">All</option>
                    <option value="-10">Employer</option>
                    <option value="-20">Search Firm</option>
                    <option value="513012">Advertising Agency</option>
                </select>
            </div>
            <input type="hidden" name="RecruiterId" value="" class="js-recruiter-id">
                <input type="submit" value="Search" id="search" class="button button--brand">
                </fieldset>
            </form>

无效的实际代码(显示整个列表):

// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
  // Prevent the original click for not reloading the whole page
  event.preventDefault();

  // Get value from search input #search
  var searchInputValue = $('#search').val();
  
  

  // Search the list and if it matches display it, else hide it
  $('.lister__item').each(function() {
    var isMatch = $('.lister__item > h3 > a:contains(' + searchInputValue + ')');
    $(this).parent().parent().toggle(isMatch);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="search" id="search" />
</div>
<div class="employers-list">
  <ul>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1208/american-international-college/" class="js-clickable-area-link pipe">American International College</a><small>
        <a href="/employer/1208/american-international-college/#listing-header">19 jobs</a></small>
      </h3>
      <img src="//careers.insidehighered.com/getasset/823f0d7b-4f21-4303-b8a3-dac30651e57c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
      <p class="no-margin">American International College is a private, coeducational institution of higher education located on a 70+ acre campus in Springfield, Massachusetts</p>
    </li>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1297911/american-national-university/" class="js-clickable-area-link pipe">American National University</a><small>
        <a href="/employer/1297911/american-national-university/#listing-header">1 job</a></small>
      </h3>
      <p class="no-margin">&nbsp;In 1886, a group of visionary educators and business leaders saw the need for an higher education institution focused on career-based training to meet workforce needs in the southeastern United States. Together they founded what is now known as Am...</p>
    </li>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1226/american-university-in-dubai/" class="js-clickable-area-link pipe">American University in Dubai</a><small>
        <a href="/employer/1226/american-university-in-dubai/#listing-header">12 jobs</a></small>
      </h3>
      <img src="//careers.insidehighered.com/getasset/f729bc47-b147-4656-9ff0-7faf9e660a4c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
      <p class="no-margin">The American University in Dubai is a private, non-sectarian institution of higher learning founded in 1995</p>
    </li>
</ul>

实际工作代码:

// Disable form since we need first the list loaded for being used
$('form').css('display', 'none');

// Get the total amount of pages
var totalPagesCount = $('.paginator__item:last-child a').attr('href').split('/')[2];

// Create a div container for adding future employers list and not being deleted later when the onclick occurs
$('<div />').addClass('employers-list').appendTo('#listing');

// Get every employer from the all the pages
for(var i=0; i<totalPagesCount; i++) {
  $.ajax({
    url: 'https://careers.insidehighered.com/employers/' + (i+1),
    type: 'get',
    cache: false,
    dataType: "html",
    success: function(results) {
      // Get all the elements and hide them
      var page = $(results).find('.lister__item').hide().detach();
      // Add them to the empty 'ul'
      $('.employers-list').append(page);
    },
    complete: function() {
      // Everything is loaded so show form again
      $('form').css('display', 'inline-block');
    }
  });
}

$.expr[":"].contains_ci = $.expr.createPseudo(function(arg) {
  return function( elem ) {
    return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
  };
});

// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
  // Prevent the original click for not reloading the whole page
  event.preventDefault();

  // Empty initial list
  $('#listing').children('li').remove();

  // Remove the paginator
  $('.paginator').remove();

  // Get value from search input
  var searchInputValue = $('#searchtext').val();

  $('.lister__item').hide().find('h3 > a:contains_ci(' + searchInputValue + ')').parents('.lister__item').show();
});

2 个答案:

答案 0 :(得分:3)

首先隐藏所有元素,然后显示匹配的元素 我还添加了contains_ci表达式,它允许搜索不区分大小写

 $.expr[":"].contains_ci = $.expr.createPseudo(function(arg) {
   return function( elem ) {
     return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
   };
 });

// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
  // Prevent the original click for not reloading the whole page
  event.preventDefault();

  // Get value from search input
  var searchInputValue = $('#search').val();

  // Search the list and if it matches display it, else hide it
  $('.lister__item').hide().find('h3 > a:contains_ci(' + searchInputValue + ')').parents('.lister__item').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="search" id="search" />
</div>
<div class="employers-list">
  <ul>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1208/american-international-college/" class="js-clickable-area-link pipe">American International College</a><small>
        <a href="/employer/1208/american-international-college/#listing-header">19 jobs</a></small>
      </h3>
      <img src="//careers.insidehighered.com/getasset/823f0d7b-4f21-4303-b8a3-dac30651e57c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
      <p class="no-margin">American International College is a private, coeducational institution of higher education located on a 70+ acre campus in Springfield, Massachusetts</p>
    </li>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1297911/american-national-university/" class="js-clickable-area-link pipe">American National University</a><small>
        <a href="/employer/1297911/american-national-university/#listing-header">1 job</a></small>
      </h3>
      <p class="no-margin">&nbsp;In 1886, a group of visionary educators and business leaders saw the need for an higher education institution focused on career-based training to meet workforce needs in the southeastern United States. Together they founded what is now known as Am...</p>
    </li>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1226/american-university-in-dubai/" class="js-clickable-area-link pipe">American University in Dubai</a><small>
        <a href="/employer/1226/american-university-in-dubai/#listing-header">12 jobs</a></small>
      </h3>
      <img src="//careers.insidehighered.com/getasset/f729bc47-b147-4656-9ff0-7faf9e660a4c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
      <p class="no-margin">The American University in Dubai is a private, non-sectarian institution of higher learning founded in 1995</p>
    </li>
</ul>

答案 1 :(得分:0)

我使用了你所拥有的内容并使用JavaScript RegExp构建了一个不区分大小写的表达式以匹配你的内容。我也使用$(this)来定位循环中的元素。

// Detect a click in the "Search" button or enter from keyboard
$('#search').on('click keyup', function(event) {
  // Prevent the original click for not reloading the whole page
  event.preventDefault();

  // Get value from search input
  var searchInputString = $('#searchtext').val();
  var regExp = new RegExp(searchInputString, 'i');

  // Search the list and if it matches display it, else hide it
  $('.lister__item').each(function() {
    var isMatch = $(this).find('h3 > a').text().match(regExp);
    $(this).toggle((isMatch) ? true : false);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchtext" type="text">
<button id="search">Search</button>
<div class="employers-list">
  <ul>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1208/american-international-college/" class="js-clickable-area-link pipe">American International College</a><small>
        <a href="/employer/1208/american-international-college/#listing-header">19 jobs</a></small>
      </h3>
      <img src="//careers.insidehighered.com/getasset/823f0d7b-4f21-4303-b8a3-dac30651e57c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
      <p class="no-margin">American International College is a private, coeducational institution of higher education located on a 70+ acre campus in Springfield, Massachusetts</p>
    </li>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1297911/american-national-university/" class="js-clickable-area-link pipe">American National University</a><small>
        <a href="/employer/1297911/american-national-university/#listing-header">1 job</a></small>
      </h3>
      <p class="no-margin">&nbsp;In 1886, a group of visionary educators and business leaders saw the need for an higher education institution focused on career-based training to meet workforce needs in the southeastern United States. Together they founded what is now known as Am...</p>
    </li>
    <li class="lister__item cf block js-clickable">
      <h3 class="lister__header">
        <a href="/employer/1226/american-university-in-dubai/" class="js-clickable-area-link pipe">American University in Dubai</a><small>
        <a href="/employer/1226/american-university-in-dubai/#listing-header">12 jobs</a></small>
      </h3>
      <img src="//careers.insidehighered.com/getasset/f729bc47-b147-4656-9ff0-7faf9e660a4c/" alt="" class="lister__logo rec-logo float-right one-quarter portable-two-fifths palm-two-fifths">
      <p class="no-margin">The American University in Dubai is a private, non-sectarian institution of higher learning founded in 1995</p>
    </li>
  </ul>
</div>

相关问题