【问题标题】:Searching in jquery在 jquery 中搜索
【发布时间】:2017-03-16 00:03:44
【问题描述】:

我有一些框 div 类,我希望当用户在搜索框中输入任何内容时,它会显示这些框和那些框(过滤它)。当前代码将在显示用户在搜索框中输入的内容之前删除所有框。谢谢!

<!-- Search box -->
<input type="text" id="txt_name"  />
<!-- Search button-->
<input type="button"  id="searchTest" value="Search"/>


<!-- Searching for the ID that the user enter -->
<script language='JavaScript' type='text/JavaScript'>

$('#searchTest').click(function() {

    // removes all the div class before displaying the results
    $('div[id*=ID_]').css('display', 'none');

    //display only whatever the user's entered
        $('div[id*=ID_]').filter(bla).css('display', 'block');
    });

    </script>



    <!-- Test boxes that needs filtering-->
    <div class="color1" id="USEID_company1_user1_Location1">
        <p> test</p>
    </div> 

    <div class="color2" id="USEID_company2_user2_Location2">
        <p> test</p>
    </div> 

【问题讨论】:

    标签: jquery html css search filter


    【解决方案1】:

    当您了解 jQuery 的 filter() 方法时,这实际上非常容易。我创建了一个小提琴来演示基础知识。根据自己的喜好进行调整。

    var $elements = $('.element');
    
    function search(value) {
        if (value == '') {
            $elements.filter(':hidden').show(); // show all hidden elements
            return;
        }
      
        $matches = $elements.filter('[data-label*="' + value.toLowerCase() + '"]'); // find search matches
    
        $elements.show().not($matches).hide(); // hide elements that don't match
    }
    
    $('#search').keyup(function() {
        search(this.value);
    });
    #search {
      width: 100%;
      padding: 0.5em 0.8em;
      box-sizing: border-box;
    }
    .element {
      padding: 0.5em;
      border-bottom: 1px solid #EEE;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" id="search" placeholder="Search the DOM..." />
    
    <div class="element" data-label="hello">Hello</div>
    <div class="element" data-label="world">World</div>
    <div class="element" data-label="car">Car</div>
    <div class="element" data-label="train">Train</div>
    <div class="element" data-label="bicycle">Bicycle</div>
    <div class="element" data-label="motor">Motor</div>
    <div class="element" data-label="plane">Plane</div>
    <div class="element" data-label="surfboard">Surfboard</div>
    <div class="element" data-label="skateboard">Skateboard</div>
    <div class="element" data-label="hovercraft">Hovercraft</div>

    您可能会注意到这段代码*=,即Attribute Contains Selector。它选择具有包含给定子字符串的值的指定属性的所有元素。在我们的例子中,子字符串代表一个搜索字符串。

    根据data-label 属性过滤掉元素。我觉得它被赋予了这种功能。如果你愿意,你也可以过滤 ID。

    最后但并非最不重要的;您可能需要考虑对search() 函数进行去抖动处理,以防止每次客户端按下某个键时都必须搜索/操作 DOM。这些操作非常耗费资源。

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 2014-02-14
      • 2012-08-11
      • 2015-03-20
      • 1970-01-01
      • 2017-02-15
      • 2013-09-03
      • 2019-05-05
      相关资源
      最近更新 更多