亲宝软件园·资讯

展开

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

Marx-link 人气:0

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

<!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.qb5200.com 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.softyun.net/code/HtmlJsRun,简单效果图如下:

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

<!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.qb5200.com 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等

希望本文所述对大家JavaScript程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论