select标签中可能会有很多数据关联,在不考虑它们顺序的情况下,解决方法
showOptions:在不考虑合法性的情况下,将options的条件全部显示在文档中,之前被选中的option还被选中,执行checkOptions():检测文档的条件合法性,不合法的选项将会被删除
$(document).ready(function(){ (function(){ var Main = {//主控对象 init:function(){ } }; var Search = {//查询对象 options: [], tempOptions:[], init: function(){ this.getOptions(); this.showOptions(); this.checkOptions(); this.eventAttach(); }, getOptions: function(){ //OM:option 码 this.options = { XWLB:{ type: "OM", n: "学位类别",//中文名字 o: [//options value,显示名字,合法条件 ["","不限",""], ["201","哲学博士学位","{type} == 1 || {type} == 5"], ["202","经济学博士","{ZYDM} == '010101' || {ZYDM} == '010102'"] ]//选项 }, ZYDM:{ type: "OM", n: "专业代码", o: [ ["","不限",""], ["010101","Max主义哲学",""], ["010102","Max主义哲学",""] ] } }; }, showOptions: function(s){ var html = "<table><tr>"; var n = 0; for(var i in this.options){ n ++; if(!(n % 3)) html += "</tr><tr>"; var op = this.options[i]; html += "<td>" + op.n + "</td>"; switch(op.type){ case "OM": { html += "<td><select id='" + i + "' name='" + i + "'>"; var temp = $("#" + i).val();//得到原来的selected被选中的选项 for(var j in op.o){ var o = op.o[j]; if(temp == o[0]){//被选中的依然被选中,如果合法 html += "<option selected='selected' id='i" + o[0] + "' value='" + o[0] + "'>" + o[1] + "</option>"; }else html += "<option id='i" + o[0] + "' value='" + o[0] + "'>" + o[1] + "</option>"; } html += "</select>"; } break; } html += "</td>"; } html += "</tr></table>"; $(".right").html(html); this.eventAttach(); }, checkOptions: function(){//将不合法的剔除掉 for(var i in this.options){ var op = this.options[i]; switch(op.type){ case "OM":{ for(var j in op.o){ var o = op.o[j]; if(o[2] != ""){//检测条件 var flag = eval(o[2].replace(/{([A-Za-z0-9_]+)}/g,"$('#$1').val()")); if(!flag) $("#i" + o[0]).remove();//若不合法,剔除吧 } } }break; } } }, getParameter: function(){ }, eventAttach: function(){ var _this = this; $(".right select").change(function(){ _this.showOptions(); _this.checkOptions(); }); }, unbindEvent: function(){ $(".right select").unbind("change"); } }; Search.init(); })(); });