根据文本框的输入动态显示/隐藏div [英] dynamically show/hide div based on the input of textbox

查看:443
本文介绍了根据文本框的输入动态显示/隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个网站上工作,
我有一个页面,其中包含一个像这样构建的人员列表:

 < div class =personsMenu> 
< div class =person>
< div class =name> John< / div>
< div class =age> 18< / div>
< / div>
< div class =person>
< div class =name>凯特< / div>
< div class =age> 24< / div>
< / div>
< div class =person>
< div class =name> Tom< / div>
< div class =age> 17< / div>
< / div>
< / div>

我也有一个文本框< input type =Textid = filterTextBox/>



使用jquery我需要执行以下操作:

当用户开始在文本框中输入时,名称不包含字符的div将会消失(某种动态过滤器,您只能看到名字中包含书写字符的人)。

所以逻辑应该是这样的:

当用户在文本框中输入一个字符(或删除一个字符)时,我们遍历所有persondivs,如果这个person中的namediv包含我们显示的字符,否则我们将它隐藏起来(.show()和.hide()in jquery)

当然,如果文本框为空,我们将显示所有内容。



可以这样做吗?

感谢您的帮助

解决方案

在每次击键时,您都可以 .toggle()每个 .person ,传递

  $('。my-textbox')一个变量,指示它是否与当前值匹配,因此应该显示。 ).keyup(function(){
var value = $(this).val();
var exp = new RegExp('^'+ value,'i');

$('。personsMenu .person')。each(function(){
var isMatch = exp.test($('。name',this).text());
$(this).toggle(isMatch);
});
));

按照您认为合适的方式修改表达式。在这个版本中,它会检查名称​​是否与输入的值开始,并且忽略大小写。

演示


I am working on a website, I have a page containing a list of persons built like this:

<div class="personsMenu">
    <div class="person">
        <div class="name">John</div>
        <div class="age">18</div>
    </div>
    <div class="person">
        <div class="name">Kate</div>
        <div class="age">24</div>
    </div>
    <div class="person">
        <div class="name">Tom</div>
        <div class="age">17</div>
    </div>
</div>

I also have a textbox <input type="Text" id="filterTextBox"/>

Using jquery i need to do the following:

When the user start typing in the textbox the divs where the "name" does not contain the characters disappears (some sort of a dynamic filter, you only see the persons who's name contains the written characters)

So the logic should be like this:

When the user type a character in the textbox (or remove one) we loop through all the "person" divs and if the "name" div inside that "person" contains the characters we show it, otherwise we hide it (.show() and .hide() in jquery)

And of course if the textbox is empty we show everything.

Can this be done?

Thanks for any help

解决方案

At every keystroke, you could .toggle() each .person, passing a variable indicating whether or not it matches the current value, and should thus be shown.

$('.my-textbox').keyup(function() {
    var value = $(this).val();
    var exp = new RegExp('^' + value, 'i');

    $('.personsMenu .person').each(function() {
        var isMatch = exp.test($('.name', this).text());
        $(this).toggle(isMatch);
    });
});​

Modify the expression as you see fit. In this version, it checks that the name starts with the value entered, and ignores casing.

Demo

这篇关于根据文本框的输入动态显示/隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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