代码之家  ›  专栏  ›  技术社区  ›  Tim

jQuery筛选

  •  4
  • Tim  · 技术社区  · 17 年前

    有没有使用jquery过滤多行选择框的方法?

    我是jquery的新手,似乎找不到实现这一点的最佳方法。

    例如,如果我有:

    <select size="10">
       <option>abc</option>
       <option>acb</option>
       <option>a</option>
       <option>bca</option>
       <option>bac</option>
       <option>cab</option>
       <option>cba</option>
       ...
    </select>
    

    我想基于选择下拉列表筛选此列表:

    <select>
       <option value="a">Filter by a</option>
       <option value="b">Filter by b</option>
       <option value="c">Filter by c</option>
    </select>
    
    1 回复  |  直到 17 年前
        1
  •  5
  •   Ian Oxley    17 年前

    类似这样的操作可能会起作用(假设您提供了“筛选依据…”,请选择一个ID 滤波器 和筛选/其他选择的ID 其他选项 ):

    $(document).ready(function() {
        $('#filter').change(function() {
            var selectedFilter = $(this).val();
            $('#otherOptions option').show().each(function(i) {
                var $currentOption = $(this);
                if ($currentOption.val().indexOf(selectedFilter) !== 0) {
                    $currentOption.hide();
                }
            });
        });
    });
    

    更新:正如@brian liang在评论中指出的那样,将<选项>标记设置为 显示:无 . 因此,下面应该为您提供一个更好的跨浏览器解决方案:

    $(document).ready(function() {
        var allOptions = {};
    
        $('#otherOptions option').each(function(i) {
            var $currentOption = $(this);
            allOptions[$currentOption.val()] = $currentOption.text();
        });
    
        $('#filter').change(function() {
            // Reset the filtered select before applying the filter again
            setOptions('#otherOptions', allOptions);
            var selectedFilter = $(this).val();
            var filteredOptions = {};
    
            $('#otherOptions option').each(function(i) {
                var $currentOption = $(this);
    
                if ($currentOption.val().indexOf(selectedFilter) === 0) {
                    filteredOptions[$currentOption.val()] = $currentOption.text();
                }
            });
    
            setOptions('#otherOptions', filteredOptions);
        });
    
        function setOptions(selectId, filteredOptions) {
            var $select = $(selectId);
            $select.html('');
    
            var options = new Array();
            for (var i in filteredOptions) {
                options.push('<option value="');
                options.push(i);
                options.push('">');
                options.push(filteredOptions[i]);
                options.push('</option>');
            }
    
            $select.html(options.join(''));
        }
    
    });