利用jQuery进行简单的数据模型绑定。 (function(global,jquery){ jquery.fn.extend(function(){ getModel:function(property){ var that=jquery(this); var result=new global.Object(); property=property||"property"; var name=that.data(pr
(function(global,jquery){ jquery.fn.extend(function(){ getModel:function(property){ var that=jquery(this); var result=new global.Object(); property=property||"property"; var name=that.data(property); if(name&&name.length>0){ var html=that.prop("tagName"); switch(html){ case "IMG": result[name]=that.attr("src"); break; case "INPUT": var type=that.attr("type"); switch(type){ case "checkbox": var checked=that.is(":checked"); result[name]=checked?"True":"False"; break; case "hidden": case "password": case "text": result[name]=that.val(); break; case "radio": if(that.is(":checked")){ result[name]=that.val(); } break; } break; case "SELECT": case "TEXTAREA": result[name]=that.val(); break; } return result; } var children=that.children(); if(children&&children.length>0){ children.each(function(index,item){ var model=jquery(item).getModel(property); for(var i in model){ result[i]=model[i]; } }); } return result; }, setModel:function(model,property){ var that=jquery(this); if(!model||typeof model!="object"){ return that; } property=property||"property"; var name=that.data(property); if(name&&name.length>0){ if(!(name in model)){ return that; } var value=model[name]; if(!value||value=="null"){ return that; } var html=that.prop("tagName"); switch(html){ case "IMG": that.attr("src",value); break; case "INPUT": var type=that.attr("type"); switch(type){ case "checkbox": var checked=value===true; checked=checked||value==="True"; checked=checked||global.Number(value)>0; that.prop("checked",checked); break; case "hidden": case "password": case "text"" that.val(value); break; case "radio": var val=that.val(); that.prop("checked",val==value); break; } break; case "SELECT": case "TEXTAREA": that.val(value); break; } return that; } var children=that.children(); if(children&&children.length>0){ children.each(function(index,item){ jquery(item).setModel(model,property); }); } return that; } }); })(window,window.jQuery);