欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

通过隐藏option实现select的联动效果

程序员文章站 2023-12-12 19:54:58
复制代码 代码如下:
复制代码 代码如下:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>untitled page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(function(){
//bind the change event
$("#droplang").unbind("change", edroplangchange).bind("change", edroplangchange);
$("#dropframe").unbind("change", edropframechange).bind("change", edropframechange);
});

//the change event of language dropdown-list
var edroplangchange = function(){
//the selected value of the language dropdown-list.
var selectedvalue = $(this).val();

//show all options.
$("#dropframe").children("span").each(function(){
$(this).children().clone().replaceall($(this)); //use the content of the <span> replace the <span>
});

//filter the data through selected value of language dropdown-list except <please select>.
//if the option is <please select>, it only needs to show all and hide nothing.
if(parseint(selectedvalue) != 0){
//hide the option whose parentid is not equal with selected value of language dropdown-list.
//the <please select> option should not be hidden.
$("#dropframe").children("option[parentid!='" + selectedvalue + "'][value!='0']").each(function(){
$(this).wrap("<span style='display:none'></span>"); //add a <span> around the <option> and hide the <span>.
});
}
};

//the change event of frame dropdown-list.
var edropframechange = function(){
//find the selected option of frame dropdown-list. set the value of language dropdown-list by selected parentid.
$("#droplang").val($(this).children("option:selected").attr("parentid"));
};
</script>
</head>
<body>
<div>
<select id="droplang">
<option selected="selected" value="0"><please select></option>
<option value="1">javascript</option>
<option value="2">java</option>
<option value="3">c#</option>
</select>
<select id="dropframe">
<option selected="selected" value="0"><please select></option>
<option value="1" parentid="1">jquery</option>
<option value="2" parentid="1">prototype</option>
<option value="3" parentid="2">struts</option>
<option value="4" parentid="2">spring</option>
<option value="5" parentid="2">velocity</option>
<option value="6" parentid="2">hibernate</option>
<option value="7" parentid="3">asp.net mvc</option>
<option value="8" parentid="3">castle</option>
</select>
</div>
</body>
</html>

这样,通过上一个下拉框的选择过滤下拉框的内容,基本实现了隐藏<option>的效果,当然,也可以把这种方法利用在下拉框级联选择的功能上,无需ajax。

该代码在ie6,ie7,chrome2,firefox3。5下验证通过。

上一篇:

下一篇: