首页 > 解决方案 > 搜索过滤器上的 jquery - 换行如果不

问题描述

这段代码工作正常,但问题是optgroup好像没有找到结果option$.wrap()但如果没有找到结果,我无法换行optgroup

$('.search').on('keyup keydown', function(){
  searchFilter($(this).val());
});

function searchFilter(value){
  $('option').each(function(){
    if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0){
      $(this).removeClass('hidden');
      $(this).removeAttr('disabled');
      
      if($(this).parent().is('span')){
        $(this).unwrap('<span>');
      }
    }else{
      $(this).addClass('hidden');
      $(this).prop('disabled', true);
      
      if(!$(this).parent().is('span')){
        $(this).wrap('<span>');
      }
    }
  });
}
.hidden{
  display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="search" />

<div class="row">
  <select multiple style="width: 150px;height:200px" id="search">
    <optgroup label="test01">
      <option>car</option>
      <option>bike</option>
      <option>cycle</option>
    </optgroup>
    <optgroup label="test02">
      <option>orange</option>
      <option>apple</option>
      <option>pineapple</option>
    </optgroup>
  </select>
</div>

标签: javascriptjqueryhtmlcss

解决方案


隐藏optgroups并且options可能不是要走的路,即使包装在span. 当我在 Safari mobile 中测试时,包裹<span style="disaply:none">不起作用。

您更好的选择是从下拉列表中删除您不想要的项目。在这样做时,您需要创建原始下拉列表的克隆,以便记录初始状态。

$(document).ready(function() {
  //Add a hidden clone
  var clone = $("#fancy").clone(true);
  clone.attr("id", "fancy_clone");
  clone.css("display", "none");
  $("body").append(clone);

  $('.search').on('keyup', function() {
    searchFilter($(this).val());
  });

  function searchFilter(value) {
    //Need a working clone - keep our clone as the original record
    var workingClone = $("#fancy_clone").clone(true);
    $("#fancy").empty();

    //Remove unwanted options
    $(workingClone).find("option").each(function() {
      if ($(this).val().toLowerCase().indexOf(value.toLowerCase()) === -1) {
        var thisParent = $(this).parents("optgroup");
        $(this).remove();

        //remove optgroup if it is empty
        if ($(thisParent).children("option").length === 0) {
          $(thisParent).remove();
        }
      }
    });

    //UPdate the actual select
    $("#fancy").append($(workingClone).html());
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" class="search" />
<select id="fancy">
  <optgroup label="test01">
    <option value="car">car</option>
    <option value="bike">bike</option>
    <option value="cycle">cycle</option>
  </optgroup>
  <optgroup label="test02">
    <option value="orange">orange</option>
    <option value="apple">apple</option>
    <option value="pinapple">pineapple</option>
  </optgroup>
</select>


推荐阅读