2010-09-03 49 views
2

我有一个带有2个列表框(HTML选择控件)的网页。 第一个列表框是多选的,包含大量的元素。页面中的Javascript数据

当我在第一个列表框中选择一个或多个元素时,第二个列表框的内容必须根据所选值进行更改。这些值必须从数据库中获取。因为选择必须立即工作,所以我必须在客户端执行所有这些操作,而无需回调/回发。这意味着在页面加载并使用JQuery处理时注入数据库的内容。

你建议如何将这些数据存储在页面中?你能指点我一些现有的解决方案吗?

我甚至不知道如何谷歌这一点。

+0

你不能使用AJAX技术吗?它不必首先加载所有的内容,但只是按需提供。 – 2010-09-03 08:17:59

+0

不幸的不是。它必须是Javascript – Germstorm 2010-09-05 10:55:54

回答

2

我将创建包含在阵列中的不同项目的对象。例如:

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

每当一个元素从第一select选择,查找与values[selectedValue]这个值,让你为其他select装箱的物品。然后你只需要为它生成HTML。

1
<!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> 
相关问题