本文实例讲述了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.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浏览器不支持这种方法的,所以改进方法:
<!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等
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript操作DOM技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。