筆者以前對於相似前端展現的,可能都是本身開發js對象,集合外加dom事件進行處理.. 近期看到相關資料,瞭解了Knockoutjs這個框架,下面來段代碼:javascript
<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();" />
獲得的效果以下:前端