- A+
所属分类:Web前端
笔者之前对于类似前端展示的,可能都是自己开发js对象,集合外加dom事件进行处理.. 近期看到相关资料,了解了Knockoutjs这个框架,下面来段代码:
<script type="text/javascript" src="~/js/knockout-3.5.1.debug.js"></script> <script type="text/javascript"> var viewModel; window.onload = function () { viewModel = { //初始化值,可以被Viewmodel监测到 userName: ko.observable('user1'), linkTel: ko.observable('15900010002'), userTypeitems: ko.observableArray([{ name: "新手", value: "100" }, { name: "老手", value: "101" }]), userTypeSelected: ko.observable("101") }; ko.applyBindings(viewModel);//完成绑定 }; function showData() {
//模拟获取值,用于提交后台等处理 alert(viewModel.userName() + "," + viewModel.linkTel() + "," + viewModel.userTypeSelected()); } </script> <div> <label>用户名</label> <input type="text" data-bind="value:userName" /><br /> <label>联系电话</label> <input type="text" data-bind="value:linkTel" /> <label>类型</label> <select data-bind="options:userTypeitems, optionsText: 'name', optionsValue: 'value',value:userTypeSelected"></select> <p data-bind="text:'您的账户信息为:'+userName()+',联系电话是:'+linkTel()+' .'"></p> </div> <input type="button" value="查看元素的值" onclick="showData();" />
得到的效果如下: