全国统一服务热线:400-633-9193

JS实现的简单下拉框联动功能示例

    网络     2018-06-04    2750

本文实例讲述了JS实现的简单下拉框联动功能。分享给大家供大家参考,具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.jb51.net JS下拉联动</title>
<script>
function setSecond(obj){
  var val = obj.value;
  if(val == 'en'){
    var sec = document.getElementById('second');
    sec.innerHTML = "<option>one</option><option>two</option>";
  }else{
    var sec = document.getElementById('second');
    sec.innerHTML = "<option>一</option><option>二</option>";
  }
}
</script>
</head>
<body>
<div>
  <select id="first" onchange="setSecond(this)">
    <option value="en">en</option>
    <option value="zh">zh</option>
  </select>
</div>
<div>
  <select id="second">
  </select>
</div>
</body>
</html>

使用在线HTML/JS/css运行工具http://tools.jb51.net/code/HtmlJsRun,简单效果图如下:

使用innerHTML,IE浏览器不支持这种方法的,所以改进方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.jb51.net JS下拉联动</title>
<script>
function setSecond(obj){
  var val = obj.value;
  if(val == 'en'){
    var sec = document.getElementById('second');
    sec.options[0] = new Option("one","one");
    sec.options[1] = new Option("two","two");
  }else{
    var sec = document.getElementById('second');
    sec.options[0] = new Option("一","one");
    sec.options[1] = new Option("二","two");//可设置循环配置,也可一个一个配置
  }
}
</script>
</head>
<body>
<div>
  <select id="first" onchange="setSecond(this)">
    <option value="en">en</option>
    <option value="zh">zh</option>
  </select>
</div>
<div>
  <select id="second">
  </select>
</div>
</body>
</html>

可以兼容火狐,IE等


  分享到:  
0.2435s