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

饮食贵在节,读书贵在精,锻炼贵在恒,节饮食养胃,多读书养胆,喜运动延生!人生需要有目标,有追求,然有所以。

本文实例讲述了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.haodaima.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.haodaima.com/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.haodaima.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程序设计有所帮助。

以上就是JS实现的简单下拉框联动功能示例。人永远不能停止梦想。梦想是心灵的养料,就像饭菜是身体的给养。人生路上咱们常会看见自我的梦想破碎了,渴望落空了,但咱们仍需做梦,否则心灵就会枯死,博爱便无法渗入心田。更多关于JS实现的简单下拉框联动功能示例请关注haodaima.com其它相关文章!

标签: 下拉框 JS