【问题标题】:Filter a list (ul>li) using dropdown list使用下拉列表过滤列表 (ul>li)
【发布时间】:2015-06-14 04:00:03
【问题描述】:

我在下面有这段代码,它根据选定的单选按钮 (JSfiddle) 过滤列表。

如何更改它,以便我可以使用下拉列表对其进行过滤(选择>选项标签)?

<input name="name" value="_a" id="_a" type="radio"/><label for="_a">A</label>
<input name="name" value="_b" id="_b" type="radio"/><label for="_f">B</label>
<input name="name" value="_ab" id="_ab" type="radio" checked="checked"/><label for="_ab">A and B</label>
<br>
<select>
    <option value="_a">A</option>
    <option value="_b">B</option>
    <option value="_ab">A and B</option>
</select>

<ul id="mylist">
<li class="_ab _a">A1</li>
<li class="_ab _a">A2</li>
<li class="_ab _b">B1</li>
<li class="_ab _b">B2</li>
</ul>
<script>
$('input').click(function() {
        var selector = $('input:radio').map(function(){ 
            return this.checked ? '.' + this.id : ''; 
        }).get().join('');
        console.log(selector);  

        var all = $('li[class^="_"]');
        if(selector.length)
          all.hide().filter(selector).show();
        else all.show();
    });
</script>

【问题讨论】:

  • 把问题放在前面,改进措辞,链接jsfiddle

标签: javascript jquery list drop-down-menu filter


【解决方案1】:

您需要为“select”标签添加一个监听器。查看.change() 规范。

【讨论】:

    【解决方案2】:

    喜欢这样吗?

    $('select').on('change', function (e) {
    
            var selector = "."+$(this).val();
            console.log(selector); 
    
            var all = $('li[class^="_"]');
            if(selector.length)
              all.hide().filter(selector).show();
            else all.show();
    });
    

    http://jsfiddle.net/8qmjjL3x/3/

    【讨论】:

      【解决方案3】:
      $('select').on('change', function (e) {
              var selector = $('option').map(function(){ 
                  return this.selected ? '.' + this.value : ''; 
              }).get().join('');
              console.log(selector);  
      
              var all = $('li[class^="_"]');
              if(selector.length)
                all.hide().filter(selector).show();
              else all.show();
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2019-05-20
        • 1970-01-01
        • 1970-01-01
        • 2011-10-26
        • 1970-01-01
        相关资源
        最近更新 更多