<!DOCTYPE html> <html lang="en"> <head> <title>OOP联动菜单</title> <meta charset="utf-8"/> <style type="text/css"> #out { text-align: center; margin: 0 auto; width: 300px; height: 300px; padding-top: 20px; background-color: grey; } div.left { margin-left: 20px; float: left; } div.right { margin-right: 20px; float: right; } </style> <script type="text/javascript"> function getByClass(oParent, sClass) { var aEle = oParent.getElementsByTagName('*'); var aResult = []; for(var i=0;i<aEle.length;i++) { if(aEle[i].className == sClass) { aResult.push(aEle[i]); } } return aResult; } /* * 个人理解: * 1.建议构造函数传参使用元素本身oDiv或者元素id,这样保证唯一性。 * 2.构造函数里面可以直接使用传递来的oDiv获取其内层元素:oDiv.getElementsByClassName("province")[0]; * 3.构造函数里面也可以直接使用传递来的id转换称元素本身后再取其内层元素: * var oDiv = document.getElementById(id); * oDiv.getElementsByClassName("province")[0] * 4.也可以定义外部函数getByClass()来实现构造函数内部取oDiv内部元素的功能 * 5.构造函数内var关键字定义的变量oDiv(临时变量,外部不可访问)和this.oDiv(成员变量,外部可以访问) * 6.OOP实现的小功能目的之一是为了模块化或者说组件化,使得页面局部设计变得简单 * */ function ProCit(oDiv,province,city){ this.pro = province; this.cit = city; //var tPro = getByClass(this.oDiv,"province"); //this.oSelPro = tPro[0]; this.oSelPro = oDiv.getElementsByClassName("province")[0]; var tCit = getByClass(oDiv,"city"); this.oSelCit = tCit[0]; for(var i= 0;i<this.pro.length;i++) { var oPt = document.createElement('option'); oPt.setAttribute("value", i); oPt.innerHTML = this.pro[i]; this.oSelPro.appendChild(oPt); } var _this = this; this.oSelPro.onchange = function(){ _this.change(); }; } ProCit.prototype.change =function() { this.oSelCit.innerHTML = ""; for (var i = 0; i < this.cit[this.oSelPro.value].length; i++) { var oPt = document.createElement("option"); oPt.setAttribute("value", i); oPt.innerHTML = this.cit[this.oSelPro.value][i]; this.oSelCit.appendChild(oPt); } }; window.onload = function(){ var province = ["please select","山东省", "浙江省","江苏省"]; var city = [ ["please select"], ["济南", "青岛", "烟台"], ["杭州", "宁波", "温州"], ["南京", "无锡", "苏州"] ]; var oDiv = document.getElementById("out"); var oProCit = new ProCit(oDiv,province,city); }; </script> </head> <body> <div id="out"> <h1>OOP联动菜单</h1> <div class="left"> <select class="province"> </select> </div> <div class="right"> <select class="city"> </select> </div> </div> </body> </html>