首页 > 代码库 > Konckout第二个实例:数组数据类型双向绑定
Konckout第二个实例:数组数据类型双向绑定
自定义js做法:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> #content1{padding: 20px;} </style> </head> <body> <div id="content1"> <select id="userNameList"> </select> <b id="selectValue"></b> </div> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/knockout30.js"></script> <script> function RenderSelectOptions(datas,selectNode){ var optionString = ""; for(var i in datas){ optionString += "<option value=http://www.mamicode.com/"+datas[i]+">"+datas[i]+"</option>"; } selectNode.html(optionString); } $(function(){ var userName = [‘党---‘,‘兴---‘,‘明---‘]; var userNameList = $(‘#userNameList‘); RenderSelectOptions(userName,userNameList); $(‘#userNameList‘).change(function(){ var selectValue = $(‘#selectValue‘); selectValue.html(userNameList.val()); }); }); </script> </body> </html>
knockout方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> #content1{padding: 20px;} </style> </head> <body> <div id="content1"> <select id="userNameList" data-bind="options:userNames,selectedOptions:selectedUserName"> </select> <b id="selectValue" data-bind="html:selectedUserName"></b> </div> <script src="js/jquery.js"></script> <script src="js/knockout30.js"></script> <script> $(function(){ var ViewModel = function(){ var self = this; self.userNames = ko.observable([‘aaa‘,‘bbb‘,‘ccc‘]); self.selectedUserName = ko.observable(""); } var currentViewModel = new ViewModel(); ko.applyBindings(currentViewModel); }); </script> </body> </html>
但:这样option上value和显示的文本都是数组里的值,当需要两个不一样时,该肿么办呢:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> #content1{padding: 20px;} </style> </head> <body> <div id="content1"> <select id="userNameList" data-bind="options:userNames,optionsText:‘Key‘,optionsValue:‘Value‘,selectedOptions:selectedUserName"> </select> <b id="selectValue" data-bind="html:selectedUserName"></b> </div> <script src="js/jquery.js"></script> <script src="js/knockout30.js"></script> <script> $(function(){ var ViewModel = function(){ var self = this; //self.userNames = ko.observable([‘aaa‘,‘bbb‘,‘ccc‘]); self.userNames = ko.observable([{Key:‘tom‘,Value:‘1‘},{Key:‘jerry‘,Value:‘2‘},{Key:‘dang‘,Value:‘3‘}]); self.selectedUserName = ko.observable(); } var currentViewModel = new ViewModel(); ko.applyBindings(currentViewModel); }); </script> </body> </html>
Konckout第二个实例:数组数据类型双向绑定
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。