使用jQuery基于data-attr过滤DOM中的元素

时间:2017-11-23 08:12:41

标签: javascript jquery

我试图根据他们的数据名称使用jQuery自动完成来过滤这些项目,但我有点卡住了。通常,我想开始在输入字段中键入文本,如果不匹配则从DOM中删除项目。非常感谢任何帮助。

笔:https://codepen.io/anon/pen/aVGjay



 $(function() {
      var item = $(".item");
    
      $.each(item, function(index, value) {
        console.log($(value).attr("data-name"));
        var everyItem = $(value).attr("data-name");
      });
    
      $("#my-input").autocomplete({
        source: everyItem, //?
        minLength: 1,
        search: function(oEvent, oUi) {
          // get current input value
          var sValue = $(oEvent.target).val();
          // init new search array
          var aSearch = [];
          // for each element in the main array
          $(everyItem).each(function(iIndex, sElement) {
            // if element starts with input value
            if (sElement.substr(0, sValue.length) === sValue) {
              // add element
              aSearch.push(sElement);
            }
          });
          // change search array
          $(this).autocomplete("option", "source", aSearch);
        }
      });
    });
    
    

  .items {
      width: 200px;
    }
    
    .item {
      background-color: red;
      margin-top: 2px;
    }

<input type="text" placeholder="Filter items" id="my-input">
   <div class="items">
      <div class="item" data-name="one">one</div>
      <div class="item" data-name="two">two</div>
      <div class="item" data-name="three">three</div>
    <div class="item" data-name="four">four</div>
 </div>
    
    
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

使用自动完成功能有点奇怪,因为它打算从提供的对象或远程数据源构建过滤选项列表,而不是从DOM内容构建过滤选项列表。

您可以通过将输入事件侦听器附加到#my-input来自行构建功能,.item依次遍历data-name元素并使用正则表达式来过滤具有匹配$(function() { var $items = $(".item"); $('#my-input').on('input', function() { var val = this.value; $items.hide().filter(function() { return new RegExp('^' + val, 'gi').test($(this).data('name')); }).show(); }); });属性的元素并显示它们,如下所示:

&#13;
&#13;
.items {
  width: 200px;
}

.item {
  background-color: red;
  margin-top: 2px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Filter items" id="my-input">
<div class="items">
  <div class="item" data-name="one">one</div>
  <div class="item" data-name="two">two</div>
  <div class="item" data-name="three">three</div>
  <div class="item" data-name="four">four</div>
</div>
&#13;
either the keyconditions or keyconditionexpression parameter must be specified in the request.
&#13;
&#13;
&#13;