开始的时候需求是根据一定条件隐藏一部分标签,类似联动效果,但是目前的html规范并没有为提供隐藏的效果,因此常用的设置display或者visibility无效。网上大部分解决方案是删除节点或置空。这显然不能够满足需求。后来经过试验,选择了利用标签包装的解决方案,基本原理如下:
当需要隐藏的时候,在标签外包装一个标签,再令标签为不可见。
当需要显示的时候,恢复其正常的状态,即,去掉外面的标签。
由于比较懒,所以利用JQuery框架来操作DOM对象和CSS,代码如下:
2 html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4
5
Untitled Page6
7
8 $(function(){
9 //Bind the change event
10 $("#dropLang").unbind("change", eDropLangChange).bind("change", eDropLangChange);
11 $("#dropFrame").unbind("change", eDropFrameChange).bind("change", eDropFrameChange);
12 });
13
14 //The change event of language dropdown-list
15 var eDropLangChange = function(){
16 //The selected value of the language dropdown-list.
17 var selectedValue = $(this).val();
18
19 //show all options.@1
20 $("#dropFrame").children("span").each(function(){
21 $(this).children().clone().replaceAll($(this)); //use the content of the replace the
22 });
23
24 //Filter the data through selected value of language dropdown-list except .
25 //If the option is , it only needs to show all and hide nothing.
26 if(parseInt(selectedValue) != 0){
27 //hide the option whose parentid is not equal with selected value of language dropdown-list.
28 //The option should not be hidden.
29 $("#dropFrame").children("option[parentid!='" + selectedValue + "'][value!='0']").each(function(){
30 $(this).wrap(""); //@2 add a around the and hide the .
31 });
32 }
33 };
34
35 //The change event of frame dropdown-list.
36 var eDropFrameChange = function(){
37 //Find the selected option of frame dropdown-list. set the value of language dropdown-list by selected parentid.
38 $("#dropLang").val($(this).children("option:selected").attr("parentid"));
39 };
40
41
42
43
44
45 <Please Select>
46 Javascript
47 Java
48 C#
49
50
51 <Please Select>
52 JQuery
53 Prototype
54 Struts
55 Spring
56 Velocity
57 Hibernate
58 ASP.NET MVC
59 Castle
60
61
62
63
这样,通过上一个下拉框的选择过滤下拉框的内容,基本实现了隐藏的效果,当然,也可以把这种方法利用在下拉框级联选择的功能上,无需Ajax。
该代码在IE6,IE7,Chrome2,Firefox3。5下验证通过。