三级联动
三级联动的核心是onchange监听文本变化
主要逻辑:当第一个下拉框的内容发生变化时 凭借该文本框的当前内容拿到对应的下一个文本框的下拉内容,并且放入下一个下拉框以供选择,依次类推
而点击提交时凭借三个下拉框的数据进行请求数据
首先我们需要三个下拉框和一个提交按钮
复制代码请更改jquery.js文件路径
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>三级联动</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
</head>
<body>
<div>
<select id="select1" name="sname1" form="form3" onchange="nianjibianhua();" style="width:200px;height:50px;" >
<!-- <option value='0'>请选择...</option> --></select>
<select id="select2"name="sname2" form="form3" style="width:200px; height:50px;" onchange="banjibianhua();"> </select>
<select id="select3" name="sname3" form="form3" style="width:200px;height:50px;" onChange="xingmingbianhua();"> </select>
<form id="rfFrame" class="" action="" method="get">
<button class="" lay-submit="" lay-filter="topsearch" onClick="tijiao();" style="height:50px; width:100px; background-color:#0FF; color:#000;">提交</button>
</form>
<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"></iframe>
</div>
</body>
</html>
JS中这样写
循环添加option 并且在变化时清空
可以使用$.get()方法配合后台完成ajax三级联动
<script type="text/javascript">
//页面加载时请求年级
window.onload=function(){
//年级放入年级框
data=["一年级","二年级","三年级"];
nianjiquanbu=[];
for(i=0;i<data.length;i++){
nianjiquanbu+="<option value=\"" + i+ "\" >"+data[i]+"</option>"
}
$("#select1").html("<option value='c' >请选择...</option> "+nianjiquanbu);
}
//当年级框值发生变化的时候
function nianjibianhua(){
$("#select2").empty();
$("#select3").empty();
xuanzhong1 = $('#select1 option:selected');
selectValue1 = xuanzhong1.val();
selectedText1 = xuanzhong1.text();
if(selectedText1=="请选择..."){
$("#select2").empty();
$("#select3").empty();
}
else{
ding_moxing_banji();
}
}
//将年级框变化请求来的数据放到班级里
function ding_moxing_banji(data){
data=["1705","1706","1707"];
banjiquanbu=[];
for(i=0;i<data.length;i++){
banjiquanbu+="<option value=\"" + i+ "\" >"+data[i]+"</option>"
}
$("#select2").html("<option value='c' >请选择...</option> "+banjiquanbu);
}
//班级值变化的时候
function banjibianhua(){
xuanzhong2 = $('#select2 option:selected');
selectValue2 = xuanzhong2.val();
selectedText2 = xuanzhong2.text();
if(selectedText2=="请选择..."){
$("#select2").empty();
$("#select3").empty();
$("#select2").html("<option value='c' >请选择...</option> "+banjiquanbu);
}else{
ding_moxing_xingming();
}
}
//将班级值变化请求来的数据放到学生框子里
function ding_moxing_xingming(data){
data=["叶凡","叶星辰","叶小天"];
xingmingquanbu=[];
//alert(JSON.stringify(data));
for(i=0;i<data.length;i++){
xingmingquanbu+="<option value=\"" + i+ "\" >"+data[i]+"</option>"
}
$("#select3").html("<option value='c' >请选择...</option> "+xingmingquanbu);
}
//获取名字框内容
function xingmingbianhua(){
xuanzhong3 = $('#select3 option:selected');
selectValue3= xuanzhong3.val();
selectedText3 = xuanzhong3.text();
}
function tijiao(){
alert(selectedText1);
alert(selectedText2);
alert(selectedText3);
}
</script>