使用jquery创建搜索过滤器

时间:2015-07-03 14:15:21

标签: jquery html

这正是我想要做的事情:

JSFiddle

但是如果我的html更加详细,我怎么能这样做呢。不能为我的生活弄清楚。所以我正在创建一个目录,每个条目都是:

<div class="search">


            <div class='listing' id='recommended' >    
                <a href="#" onclick="toggle_visibility('interactive');">
                <h3>Violet Label</h3>
                <h3>London</h3></a>

                <div id="interactive" style="display:none;">
                    <div class="web"><p><a href="#" onclick="openDeviceBrowser ('http://violetjobs.com')">
                    violetjobs.com</a></p></div>
                    <div class="phone"><p><a href="Tel:07855010244">Tel: 07855010244</a></p></div>
                    <div class="email"><p><a href="mailto:info@violetjobs.com">info@violetjobs.com</a></p></div>

                    <p>Submission Guidelines: None specified</p>
                    <p>Genres: Minimal Tiny Techno, Downbeat Nado House</p>
                </div>  

            </div>

我需要一个在您输入时过滤掉的搜索框。所以这个被称为紫罗兰标签。当用户搜索时,比如按“V”,这整个应该保留,其他不以V开头的应该消失。

我确定它很简单!??

1 个答案:

答案 0 :(得分:0)

让我们来看看你的例子中发生了什么 -

$('#box').keyup(function(){

   //get the current typed text
   var valThis = $(this).val().toLowerCase();

    //loop round all the list items
    $('.navList>li').each(function(){

    //find the text in the list item
    var text = $(this).text().toLowerCase();

    //show or hide it if the text matches
    (text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();

   });
});

在更新的示例中,您希望匹配<h3>Violet Label</h3>中的内容,而不是匹配列表项内的文本。通过向其添加一个类 - <h3 class='title'>...</h3>

,可以轻松找到它

您可以围绕每个.listing循环并检查标题 -

$('#box').keyup(function(){

   //get the current typed text
   var valThis = $(this).val().toLowerCase();

    //loop round all the listings
    $('.listing').each(function(){

    //find the text in the header item
    var text = $(this).find('.title').text().toLowerCase();

    //show or hide it if the text matches
    (text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();

   });
});

然而 - 这不是特别有效,你可能会更好地查看一些模板库,甚至是一个小角度应用程序 - 过滤非常简洁。

相关问题