【问题标题】:dynamically show/hide div based on the input of textbox根据文本框的输入动态显示/隐藏 div
【发布时间】:2012-06-27 14:57:12
【问题描述】:

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

<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>

我还有一个文本框&lt;input type="Text" id="filterTextBox"/&gt;

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

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

所以逻辑应该是这样的:

当用户在文本框中键入一个字符(或删除一个字符)时,我们会遍历所有“person” div,如果该“person”中的“name”div 包含我们显示的字符,否则我们将其隐藏( jquery 中的 .show() 和 .hide())

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

这个可以吗?

感谢您的帮助

【问题讨论】:

  • 是的,这可以做到,到目前为止你用 jQuery 尝试过什么(你有什么代码)?

标签: jquery html


【解决方案1】:

在每次击键时,您可以.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);
    });
});​

根据需要修改表达式。在这个版本中,它检查名称​​以输入的值开始,并忽略大小写。

Demo

【讨论】:

  • 如何通过检查这些元素的子元素来使其工作?但是,只隐藏了整个盒子。因此,如果 div 中有标签,它会搜索所有标签并基于此隐藏/显示整个 div。我的测试不断让我得到奇怪的结果。
  • @BryantFrankford:如果我的理解正确,应该足以确保每场比赛的所有祖先节点也是可见的。查看this demoif(isMatch) 部分
  • new i (RegExp('^' + value, 'i');) 是什么意思。我必须为整个文本搜索做什么。上面的代码正在运行,但与开始文本匹配。我想在文本行的任何地方匹配文本
  • @Inderjeet:^ 匹配字符串的开头。使用RegExp(value, 'i')
【解决方案2】:

这里有一些东西可以帮助您入门。我敢肯定它远非完美,但您还没有展示您已经尝试过的内容以及您的问题中出了什么问题。

$("#filterTextBox").on("keyup", function () {
    var search = this.value;
    $(".person").show().filter(function () {
        return $(".name", this).text().indexOf(search) < 0;
    }).hide();        
});​​​​​​​​​​​​​

这是working example

【讨论】:

    【解决方案3】:
    $('input').keyup(function(){
      var value = this.value
      $('.person')
        .hide()
        .children('.name')
        .filter(function(){
          var re = new RegExp(value)
          return re.test($(this).text())
        })
        .parent()
        .show()
    })
    

    【讨论】:

      【解决方案4】:

      既然你用 jQuery 标记了这个,我强烈推荐他们的Autocomplete UI Control。我已经在几个项目中使用了它,您可以更新搜索功能以使用这样的本地数据存储。附带说明一下,您可能需要考虑使用 &lt;ul&gt;'s 和 &lt;li&gt;'s...

      代码示例

      //Search-As-You-Type
      $(id).find('input').autocomplete({
          minLength: 2,
          focus: function( event, ui ) {},
          select: function( event, ui ) {},
          source: function(request, response){
              //here is where you want to call your custom function
              findSite(request.term);             
          }
      });
      

      【讨论】:

        【解决方案5】:

        最近我需要这种类型的工作,我找到了一个不错的解决方案。看到这个jQuery popout div next to element of my choice

        【讨论】:

          【解决方案6】:

          此代码搜索整个字符串

          $( '#input-text' ).keyup( function () {
              var value = $( this ).val();
             $( '#filter-parant > .filter-div' ).each( function () {
                  $('.filter-div:contains("' + value + '")').show();
                  $('.filter-div:not(:contains("' + value + '"))').hide();
          
              } );
          } );
          

          希望对您有所帮助

          【讨论】:

            【解决方案7】:

            这是您应该考虑使用和创建的脚本。您还应该使用&lt;ul&gt;&lt;li&gt;

            (function($){
                $.tzFilter = function(jq, phrase, type, column, ifHidden){
                    var new_hidden = false;
                    if(this.last_phrase === phrase){
                        return false;
                    }
            
                    if(!type){
                        type = 'ul';
                    }
            
                    var phrase_length = phrase.length;
                    var words = phrase.toLowerCase().split(' ');
            
                    var matches = function(elem){
                        elem.show()
                    }
                    var noMatch = function(elem){
                        elem.hide();
                        new_hidden = true
                    }
                    var getText = function(elem){
                        return elem.text()
                    }
            
                    if(column){
                        var index = null;
                        if(type == 'table'){
                            jq.find('thead > tr:last > th').each( function(i){
                                if( $.trim($(this).text()) == column ){
                                    index = i; return false;
                                }
                            });
                        } else if (type == 'ul'){
                            jq.find("li").each(function(i){
                                if(!$(this).attr('display', 'none')){
                                    if( $.trim($(this).text()) == column ){
                                    index = i; return false;
                                    }
                                }
                            });
                        }
            
                        if(index == null){
                            throw('Index non trouvée: ' + column + '')
                        }
            
                        if(type == 'table'){
                            getText = function(elem){
                                return jQuery(elem.find(('td:eq(' + index + ')')  )).text();
                            }
                        } else if (type == 'ul') {
                            getText = function(elem){
                                return jQuery(elem.find(('"li:eq(' + index + ')')  )).text();
                            }
                        }
                    }
            
                    // On a simplement ajouté une lettre, on va regarder pour le nouveau mot, sans devoir tout regarder à nouveau
                    if((words.size > 1) && (phrase.substr(0, phrase_length - 1) === this.last_phrase)){
                        if(phrase[-1] === ' '){
                            this.last_phrase = phrase;
                            return false;
                        }
            
                        // On va chercher uniquement pour le nouveau mot
                        var words = words[-1];
            
                        // On cache uniquement les tables visibles
                        matches = function(elem) {;}
            
                        if(type == 'table'){
                            var elems = jq.find('tbody > tr:visible');
                        } else if (type == 'ul'){
                            var elems = jq.find('li:visible');
                        }
                    } else {
                        new_hidden = true;
            
                        if(type == 'table'){
                            var elems = jq.find('tbody > tr')
                        } else if (type == 'ul') {
                            var elems = jq.find('li')
                        }
                    }
            
            
                    elems.each(function(){
                        var elem = $(this);
                        $.tzFilter.has_words(getText(elem), words, false) ? matches(elem) : noMatch(elem);
                    });
            
                    last_phrase = phrase;
            
                    if(ifHidden && new_hidden){
                        ifHidden();
                    }
                    return jq;
                };
            
                // On cache pour accélérer le tout
                $.tzFilter.last_phrase = ""
            
                $.tzFilter.has_words = function(str, words, caseSensitive){
                    var text = caseSensitive ? str : str.toLowerCase();
                    for (var i=0; i < words.length; i++){
                        if(text.indexOf(words[i]) === -1){
                            return false;
                        }
                    }
                    return true;
                }
            })(jQuery);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-10-30
              • 2020-02-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多