简体   繁体   English

使用jQuery进行实时搜索时如何隐藏div

[英]How to hide divs when livesearching with jQuery

I'm trying to make a function in jQuery that, while typing, it livesearch divs with the same h5 element (I know it could be a class or an id , but I'm making it like that because reasons). 我正在尝试在jQuery中创建一个函数,在键入时,它使用相同的h5元素进行livesearch div(我知道它可以是id ,但是由于某种原因,我这样做了)。 And when the searchbox is empty again, everything should be back to normal. 当搜索框再次为空时,所有内容应恢复正常。

I'm using Bootstrap panels to achieve this also. 我正在使用Bootstrap面板来实现此目的。

My jQuery code is this. 我的jQuery代码是这样。 I got it from another answer here, but modified a little for me needs: 我是从这里的另一个答案中得到的,但是为我的需求做了一些修改:

//Se supone que busca. Lo plagié vilmente.
$("#busqueda").keyup(function(){

// Retrieve the input field text and reset the count to zero
var filter = $(this).val();

// Loop through the comment list
$(".nombre").each(function(){

    // If the list item does not contain the text phrase fade it out
    if ($(this).attr("h5").contains(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();

        alert(filter);

    // Show the list item if the phrase matches and increase the count by 1
    } else {
        $(this).show();
    }
});
});

My HTML code is: 我的HTML代码是:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 p1" data-clickstate="0">
            <div class="panel panel-default" id="panel_1">
                <div class="panel-body" style="display: inline" id="cat_1">

                    <div class="icono">
                        <img src="media/iconos/motores_busqueda.png" alt="">
                    </div>
                    <div class="nombre-y-des">
                        <div>
                            <h5 class="nombre">Motores de búsqueda</h5>
                        </div>
                        <div class="des">
                            <p>Servicios de búqueda de páginas web.</p>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <div class="col-sm-4 col-md-4">
            <div class="panel panel-default" id="panel_2">
                <div class="panel-body" id="cat_2" style="display: inline">
                    <div class="icono">
                        <img src="media/iconos/navegadores.png" alt="">
                    </div>
                    <div class="nombre-y-des">
                        <div>
                            <h5 class="nombre">Navegadores</h5>
                        </div>
                        <div class="des">
                            <p>Programa que permite navegar por internet, renderizado páginas HTML en contenido visual y
                                comprensible.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-4 col-md-4">
            <div class="panel panel-default" id="panel_3">
                <div class="panel-body" id="cat_3" style="display: inline">
                    <div class="icono">
                        <img src="media/iconos/servidores_correo.png" alt="">
                    </div>
                    <div class="nombre-y-des">
                        <div>
                            <h5 class="nombre">Servidores de correo</h5>
                        </div>
                        <div class="des">
                            <p>Servicio que permite enviar y recibir mensajes mediante sistemas de comunicación eletrónicos
                                en línea.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

The jQuery code should be looking the h5 attribute to compare it with what is being typed, and therefore hide all other divs. jQuery代码应查找h5属性,以将其与输入的内容进行比较,因此隐藏了所有其他div。 Tho I think I'm missing something or I'm doing it all wrong. 我认为我缺少某些东西,或者我做错了所有事情。 I'm not that experienced with jQuery. 我对jQuery并不了解。

This is the searchbox: 这是搜索框:

<div id="contenido">
    <div class="container">
        <div class="row" id="busqueda">
            <div class="col-md-12 text-center ">
                <div id="custom-search-input">
                    <div class="input-group col-md-12">
                        <input type="text" class="form-control input-lg" placeholder="Actividad a realizar, categorías, etc. (no olvides escribir los acentos correctamente ;~)"
                            id="inputBusqueda" />
                        <span class="input-group-btn">
                            <button class="btn btn-info btn-lg" type="button">
                                <i class="glyphicon glyphicon-search"></i>
                            </button>
                            </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

attr("h5") isn't going to work, and you don't need it because you've already selected the h5 elements with the class "nombre". attr(“ h5”)不起作用,并且您不需要它,因为您已经选择了“ nombre”类的h5元素。

contains() may not do what you think it does. contains()可能不会执行您认为的操作。 it's for checking parent/child relationship in the DOM (you may be confusing it with :contains ) 它用于检查DOM中的父/子关系(您可能将它与:contains混淆了)

To get the text of the nombre elements use just 要获取nombre元素的文本,只需使用

$(this).text()

or 要么

$(this).html()

Then run your regex on that. 然后在上面运行您的正则表达式。

 // Case insensitive :contains | https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/ $.expr[":"].contains = $.expr.createPseudo(function(arg) { return function(elem) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); $(document).ready(function() { //Se supone que busca. Lo plagié vilmente. $("#inputBusqueda").keyup(function() { // Retrieve the input field text and reset the count to zero var filter = $(this).val(); // Loop through the comment list $(".col-sm-4.col-md-4").each(function() { if ($(this).find('h5').is(':contains("' + filter + '")')) { $(this).show(); } else { $(this).hide(); } }); }); }); 

  • Extra: the first thing is an snippet I found because I think users tend to search in lowercase; 另外:第一件事是我发现的一个片段,因为我认为用户倾向于小写搜索; and it allows to search with insensitive case. 并允许以不区分大小写的形式进行搜索。
  • Changed the id of the search input ( #inputBusqueda ). 更改了搜索输入的ID( #inputBusqueda )。
  • Redid all the "contains" part. 重做所有“包含”部分。 In your code you were using $.contains() but like @Stu Cartwright said it's used for comparing element relations and such. 在您的代码中,您使用的是$.contains()但就像$.contains() Cartwright所说的那样,它用于比较元素关系等。
  • The way I did it is simple: for each "column" we check if an h5 child :contain s the filter value, if so we show it, else we hide it. 我这样做的方法很简单:对于每个“列”,我们检查h5 child :contain h5是否:contain filter值,如果是,则显示该值,否则将其隐藏。

Check JSFiddle demo . 检查JSFiddle演示 Also if you want the search to be case sensitive, just get rid of the first part. 另外,如果您希望搜索区分大小写,则只需删除第一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM