过滤列表在键入与jQuery [英] Filtering a list as you type with jQuery

查看:188
本文介绍了过滤列表在键入与jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正打算创建一个使用一个简单的数据库查询我的web应用程序的用户的无序列表,但当时正打算让人们通过键入此人的名字,他们正在寻找到一个文本输入。过滤此列表中上下

I was planning to create an unordered list of users of my web application using a simple database query, but then was planning to let people filter this list down by typing the person's name they're looking for into a text input.

我希望使用jQuery的字符串在输入框中输入的任何匹配内部的列表项之一,然后隐藏其他的,可能是通过动态地应用新的类来包含匹配的字符串的那些,和隐藏所有其他不包含该类

I was hoping to use jQuery to match the string in the input box to any inside one of the list items, then hide the other ones, maybe by applying a new class dynamically to the ones that contain the matching string, and hiding all others that don't contain that class.

有谁知道一个好办法做到这一点?

Does anyone know of a good way to do this?

推荐答案

假设你的 UL 有一个 ID 的thelist ,以下将做的一种方式。

Assuming that your ul has an id of theList, the following would be one way of doing it.

<input type="text" onkeyup="filter(this)" />

<script language="javascript" type="text/javascript">
    function filter(element) {
        var value = $(element).val();

        $("#theList > li").each(function() {
            if ($(this).text().search(value) > -1) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        });
    }
</script>

另外的依据是什么马雷克Tihkan贴,你可以更换每个()循环用下面的一个更简洁的版本。不知道这是否会表现得更好或更差。

Alternatively for a more concise version based on what Marek Tihkan posted you could replace the each() loop with the following. Not sure whether this would perform better or worse.

$('#theList > li:not(:contains(' + value + '))').hide(); 
$('#theList > li:contains(' + value + ')').show();

这篇关于过滤列表在键入与jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆