Konckout第二个实例:数组数据类型双向绑定
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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="+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第二个实例:数组数据类型双向绑定的主要内容,如果未能解决你的问题,请参考以下文章