在网上很多网友问,关于实现在一个select列表中选择一个项目,在另一个select选项动态更新的情况。其实他的原理很简单的,只有记住几个主要的要点就可以。
下面的例子给出了一个完整的演示。由于看例子比我解说更容易理解,所以我就废话少说,把代码贴出,希望对大家需要的网友有一点帮助。
<html>
<head>
<title> new document </title>
<meta name="generator" content="editplus">
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<style type="text/css">
body{font-family:courier new, courier}
select{font-size:8pt;font-family:courier new, courier}
input{font-size:8pt;font-family:courier new, courier}
</style>
<script language="javascript">
<!--
var name=new array(3);
var value=new array(3);
name[1]=new array("zosatapo1","zosatapo2","zosatapo3","zosatapo4");
name[2]=new array("reic yang1","reic yang2","reic yang3","reic yang4");
function change()
{
selindex=document.all("test").selectedindex;
if(document.all("test").selectedindex==0)
return;
for(i=document.all("test").options.length-1;i>-1;i--)
{
document.all("test").options.remove(i);
}
for(i=0;i<name[selindex].length;i++)
{
document.all("test").options.add(new option(name[selindex][i],"name"+i));
}
}
function changeex(){
for(i=document.all("sub").options.length;i>0;i--)
{
document.all("sub").options.remove(i-1);
}
if(document.all("main").selectedindex==0){
document.all("sub").options.add(new option("==========","-1"));
return;}
selindex=document.all("main").selectedindex;
for(i=0;i<name[selindex].length;i++)
{
document.all("sub").options.add(new option(name[selindex][i],"name"+i));
}
}
function reset(){
for(i=document.all("test").options.length-1;i>-1;i--)
{
document.all("test").options.remove(i);
}
document.all("test").options.add(new option("==========","-1"));
document.all("test").options.add(new option("zosatapo","1"));
document.all("test").options.add(new option("reic yang","2"));
}
function display(object){
alert(object.options[object.selectedindex].text+" "+object.options[object.selectedindex].value);
}
//-->
</script>
</head>
<body bgcolor="#ffffff">
first sample:<br><font color="blue">all items will change after you selected!</font><br>
<select id="test" onchange="change();">
<option value="-1" selected>==========
<option value="1">zosatapo
<option value="2">reic yang
</select><input name="reset select" type="button" value="reset select" onclick="reset();" ><br><br>
second sample:<br><font color="blue">you selected item in main select will change the sub select content!</font><br>
main select:<select id="main" onchange="changeex();">
<option value="-1" selected>==========
<option value="1">zosatapo
<option value="2">reic yang
</select>
sub select:<select id="sub" onchange="display(this);">
<option value="-1" selected>==========
</select><br><br>
</body>
</html>