【问题标题】:jQuery FilteringjQuery 过滤
【发布时间】:2010-10-25 07:15:32
【问题描述】:

有没有办法使用 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>

【问题讨论】:

    标签: javascript jquery filtering


    【解决方案1】:

    这样的事情可能会奏效(假设你给你的“过滤方式...”选择一个 filter 的 id 并且过滤/其他选择一个 otherOptions的 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 在 cmets 中指出的那样,您可能在将

    $(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(''));
        }
    
    });
    

    【讨论】:

    • 我认为这不起作用,因为您无法隐藏该选项元素。
    • @Brian Liang 在发布之前我确实在 Firefox 中进行了快速测试,它确实有效。但是我刚刚检查了 Opera、Safari、Chrome 和 IE 8,你是对的:它在这些浏览器中不起作用。
    • Tim,我在 Chrome/IE 中尝试过它,它就像一个魅力。干得好伊恩!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2016-10-07
    • 2011-02-09
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多