代码之家  ›  专栏  ›  技术社区  ›  Germstorm Pierre-Alain Vigeant

页面中的Javascript数据

  •  2
  • Germstorm Pierre-Alain Vigeant  · 技术社区  · 14 年前

    我有一个网页,有两个列表框(HTML选择控件)。 第一个列表框是multi-select,包含大量元素。

    我甚至不知道怎么用谷歌搜索这个。

    3 回复  |  直到 9 年前
        1
  •  2
  •   Felix Kling    14 年前

    我将创建一个对象来保存数组中的不同项。例子:

    var values = {
        cat1: ["item1", "item2", ...],
        cat2: ["item1", "item2", ...]
    }
    

    select ,用 values[selectedValue] 选择

        2
  •  1
  •   Darin Dimitrov    14 年前
    <!DOCTYPE html>
    <html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript">
        // Simple plugin that compares two arrays
        jQuery.fn.compare = function(t) {
            if (this.length != t.length) { 
                return false; 
            }
            var a = this.sort(),
                b = t.sort();
            for (var i = 0; t[i]; i++) {
                if (a[i] !== b[i]) { 
                    return false;
                }
            }
            return true;
        };
    
    
        // Those rules should be fetched from the server
        var rules = [ 
            // select the first value if 1, 2 and 5 are selected
            { value: '1', selectedValues: [ '1', '2', '5' ] }, 
            // select the second value if 2 and 4 are selected
            { value: '2', selectedValues: [ '2', '4' ] }, 
            // select the third value if 3 is selected
            { value: '3', selectedValues: [ '3' ] }
        ];
    
        $(function() {
            // whenever the selection in the multiselect box changes:
            $('#first').change(function() {
                // get the array of all selected elements
                var selectedValues = $(this).val();
    
                // verify if this array matches any of the defined rules
                $(rules).each(function(index, rule) {
                    if ($(selectedValues).compare(rule.selectedValues)) {
                        // if we have a match select the corresponding value in the second list
                        $('#second').val(rule.value);
                    }
                })
            });
        });
        </script>
    
    </head>
    <body>
    
    <select multiple="multiple" id="first">
        <option value="1">value1</option>
        <option value="2">value2</option>
        <option value="3">value3</option>
        <option value="4">value4</option>
        <option value="5">value5</option>
    </select>
    
    <select id="second">
        <option value="1">value1</option>
        <option value="2">value2</option>
        <option value="3">value3</option>
    </select>
    
    </body>
    </html>