代码:
function Product(ProductID,ProductName,ProductNum,Result,Price) { this.ProductID = ko.observable(ProductID); this.ProductName = ko.observable(ProductName); this.ProductNum = ko.observable(ProductNum); this.Result = ko.observable(Result); this.Price = ko.observable(Price); }
self.add = function (o) { self.isDetail(true); self.selectedItem(new Sale()); $.ajax({ url: "/api/CommonApi?API=GetProductListByBuy", type: "get", dataType: "json", success: function (data) { var list = data.ApiParamObj; var arr = []; $(list).each(function () { var ProductNum = $(this)[0].ProductNum; var Result = $(this)[0].Result; var Price = $(this)[0].Price; var ProductID = $(this)[0].ProductID; var ProductName = $(this)[0].ProductName; //console.log(Price); //self.ProductList().push(new Product(ProductNum, Result, Price)); arr.push(new Product(ProductID, ProductName, ProductNum, Result, Price)); //self.ProductList.push(new Product(ProductID, ProductName, ProductNum, Result, Price)); }) //console.dir(arr); self.ProductList(arr); //self.ProductList = ko.observableArray(arr); //console.log(self.ProductList().length); //console.dir(self.ProductList()); } }); $("#formDialog").valid(); }
对每一个属性进行监控,组成数组对整个数组进行监控
计算总数量,总金额
self.TotalNum = ko.computed(function () { //console.log("ffff"); //console.dir(self.ProductList()); var total = 0; ko.utils.arrayForEach(self.ProductList(), function (item) { if (item.Result()) { var value = parseFloat(item.ProductNum()); if (!isNaN(value)) { total += value; } } }); return total.toFixed(0); }); self.TotalAmount = ko.computed(function () { var total = 0; ko.utils.arrayForEach(self.ProductList(), function (item) { if (item.Result()) { var value = parseFloat(item.ProductNum() * item.Price()); if (!isNaN(value)) { total += value; } } }); return total.toFixed(2); })
html代码:
<div class="row"> <div class="form-group col-xs-12"> <label class="control-label col-md-2">产品:</label> <div class="col-md-10" data-bind="visible: ProductList().length > 0,foreach:ProductList"> <div class="dvcls"> <input type="checkbox" class="chk" data-bind="checked:Result,value:ProductID,attr:{ name: $index },enable:$parent.isDetail" /> <span data-bind="text:ProductName"></span> 价格:<span data-bind="text:Price"></span> <input type="number" style="width:40px" min="1" data-bind="value:ProductNum,valueUpdate:'keyup',visible:Result,enable:$parent.isDetail" /> </div> </div> </div> </div>
效果图:
整个代码:
@{ Model.Scripts = new string[] { "~/Scripts/paginationViewModel.js", "/Views/BoxSale/BoxSale.js" }; } <style type="text/css"> .dvcls{ display:inline-block; width:290px; padding-left:0px; } </style> <div class="page-content" style="padding-top: 0;"> <!-- BEGIN PAGE CONTENT--> <div class="row"> <div class="col-md-12"> <!-- BEGIN EXAMPLE TABLE PORTLET--> <div class="portlet box blue-hoki" style="background-color: white"> <div class="portlet-title"> <div class="caption" style="font-weight:bold;margin:10px;"> 销售记录 </div> <div class="tools"></div> </div> <div class="portlet-body"> <a href="javascript:void(0)" class="label label-info" style="margin:10px;" data-toggle="modal" data-target="#dvDialog" data-bind="click:add">销售礼品</a> <table class="table table-striped table-bordered table-hover" id="tblCompany" style="margin:10px; text-align: center;"> <thead> <tr style="background-color:#00adef"> <th> 序号 </th> <th> 客户 </th> <th> 礼品数量 </th> <th> 总金额 </th> <th> 编辑 </th> </tr> </thead> <tbody data-bind="visible: SaleList().length > 0,foreach: SaleList"> <tr> <td data-bind="text:$index()+1"></td> <td data-bind="text:Name"></td> <td data-bind="text:Num"></td> <td data-bind="text:Amount.toFixed(2)"></td> <td> <a class="label label-info" data-toggle="modal" data-target="#dvDialog" data-bind="click:$parent.edit">查看</a> <a class="label label-info" data-bind="click:$parent.remove">删除</a> </td> </tr> </tbody> </table> <div class="row datatables_paginate paging_full_numbers" style="text-align:center;" data-bind="visible: pages().length > 0"> <div class="small-12 columns" data-bind="template: 'PaginationTemplate'"></div> </div> </div> </div> <!-- END EXAMPLE TABLE PORTLET--> </div> </div> <!-- 编辑公司 --> <div class="modal fade bs-example-modal-lg" tabindex="-1" id="dvDialog" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" style="margin-top:10%"> <div class="modal-content" style="width:860px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h4 class="modal-title" style="margin-left:4%;color:#00adef"> <i class="icon-docs" style="font-size: 24px;"></i> <span data-bind="if:selectedItem().SaleRecordID==null">新建</span> <span data-bind="if:selectedItem().SaleRecordID!=null">查看</span> </h4> </div> <div class="modal-body" style="border-top: 1px solid #EFEFEF; width: 90%;margin-left:5%"> <form id="formDialog" name="formDialog" class="form-horizontal"> <div class="row"> <div class="form-group col-xs-12"> <label class="control-label col-md-2">客户:</label> <div class="col-md-10"> <select class="form-control" required name="fCustomerID" data-bind="options:customersList,optionsCaption: '请选择客户', optionsText:function(item){ return item.NameMobile}, optionsValue:function(item){ return item.ID }, value:selectedItem().CustomerID,enable:isDetail"></select> </div> </div> </div> </form> <div class="row"> <div class="form-group col-xs-12"> <label class="control-label col-md-2">产品:</label> <div class="col-md-10" data-bind="visible: ProductList().length > 0,foreach:ProductList"> <div class="dvcls"> <input type="checkbox" class="chk" data-bind="checked:Result,value:ProductID,attr:{ name: $index },enable:$parent.isDetail" /> <span data-bind="text:ProductName"></span> 价格:<span data-bind="text:Price"></span> <input type="number" style="width:40px" min="1" data-bind="value:ProductNum,valueUpdate:'keyup',visible:Result,enable:$parent.isDetail" /> </div> </div> </div> </div> <div class="row"> <div class="form-group col-xs-12"> <label class="control-label col-md-2">总数:</label> <div class="col-md-4"> <span data-bind="text:TotalNum"></span> </div> <label class="control-label col-md-2">总金额:</label> <div class="col-md-4"> <span data-bind="text:TotalAmount"></span> </div> </div> </div> <div class="modal-footer" data-bind="visible:isDetail"> <button style="width: 42%;" type="button" class="btn blue" data-bind="click:function(){save();}"> 确定 </button> <button style="width: 42%;" type="button" class="btn blue" data-dismiss="modal">取消</button> </div> </div> </div> </div> </div> </div> <script type="text/html" id="PaginationTemplate"> <ul class="pagination" data-bind="visible: pages().length > 0"> <li><a data-bind="click: goToFirst"><<</a></li> <li><a data-bind="click: goToPrev"><</a></li> <!--ko if:showStartPagerDot--> <li><a data-bind="click:StartPageDot">...</a></li> <!--/ko--> <!--ko foreach:pages--> <li data-bind="css: { 'active': $data == $parent.currentPage() }"> <a data-bind="text: $data, click: $parent.goToPage.bind($data, $data)"></a> </li> <!--/ko--> <!--ko if:showEndPagerDot--> <li><a data-bind="click:EndPageDot">...</a></li> <!--/ko--> <li><a data-bind="click: goToNext">></a></li> <li><a data-bind="click: goToLast">>></a></li> </ul> </script>
$(function () { Date.prototype.Format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时 "H+": this.getHours(), "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "f": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } function GetNow() { return new Date().Format("yyyy-MM-dd HH:mm:ss"); } function Guid() { var guid = ""; for (var i = 1; i <= 32; i++) { var n = Math.floor(Math.random() * 16.0).toString(16); guid += n; if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) guid += "-"; } return guid; } var isT = false; var isS = false; function Product(ProductID,ProductName,ProductNum,Result,Price) { this.ProductID = ko.observable(ProductID); this.ProductName = ko.observable(ProductName); this.ProductNum = ko.observable(ProductNum); this.Result = ko.observable(Result); this.Price = ko.observable(Price); } function Sale() { this.SaleRecordID = null; this.CustomerID = ""; this.Name = ""; this.Amount = 0; this.Num = 0; } var model = function () { var self = this; self.ProductList = ko.observableArray([]); self.selectedItem = ko.observable(); self.customersList = ko.observableArray(); self.SaleList = ko.observableArray(); self.isDetail = ko.observable(true); self.remove = function (o) { Confirm('你确定要删除该记录吗?').on(function () { var data = { SaleRecordID: o.SaleRecordID, UpdateTime: GetNow(), UpdateBy: $User.UserID, IsDelete: 1 }; $.ajax({ url: "/api/CommonApi?API=DelSale", type: "put", data: { ApiParamObj: JSON.stringify(data) }, dataType: "json", success: function (data) { if (data.Success) { Alert("删除成功").on(function () { self.goToPage(1); }) } } }); }); } self.add = function (o) { self.isDetail(true); self.selectedItem(new Sale()); $.ajax({ url: "/api/CommonApi?API=GetProductListByBuy", type: "get", dataType: "json", success: function (data) { var list = data.ApiParamObj; var arr = []; $(list).each(function () { var ProductNum = $(this)[0].ProductNum; var Result = $(this)[0].Result; var Price = $(this)[0].Price; var ProductID = $(this)[0].ProductID; var ProductName = $(this)[0].ProductName; //console.log(Price); //self.ProductList().push(new Product(ProductNum, Result, Price)); arr.push(new Product(ProductID, ProductName, ProductNum, Result, Price)); //self.ProductList.push(new Product(ProductID, ProductName, ProductNum, Result, Price)); }) //console.dir(arr); self.ProductList(arr); //self.ProductList = ko.observableArray(arr); //console.log(self.ProductList().length); //console.dir(self.ProductList()); } }); $("#formDialog").valid(); } self.TotalNum = ko.computed(function () { //console.log("ffff"); //console.dir(self.ProductList()); var total = 0; ko.utils.arrayForEach(self.ProductList(), function (item) { if (item.Result()) { var value = parseFloat(item.ProductNum()); if (!isNaN(value)) { total += value; } } }); return total.toFixed(0); }); self.TotalAmount = ko.computed(function () { var total = 0; ko.utils.arrayForEach(self.ProductList(), function (item) { if (item.Result()) { var value = parseFloat(item.ProductNum() * item.Price()); if (!isNaN(value)) { total += value; } } }); return total.toFixed(2); }) self.edit = function (o) { self.isDetail(false); self.selectedItem(o); $.ajax({ url: "/api/CommonApi?API=GetBoxSaleRecordBySaleRecordID", type: "get", data:{"SaleRecordID":o.SaleRecordID}, dataType: "json", success: function (data) { var list = data.ApiParamObj; var arr = []; $(list).each(function () { var ProductNum = $(this)[0].ProductNum; var Result = 1; var Price = $(this)[0].Price; var ProductID = $(this)[0].ProductID; var ProductName = $(this)[0].ProductName; arr.push(new Product(ProductID, ProductName, ProductNum, Result, Price)); }) self.ProductList(arr); } }); console.dir(self); } self.insertRecord = function (guid) { ko.utils.arrayForEach(self.ProductList(), function (item) { if (item.Result()) { var data = {}; data.ProductID = item.ProductID(); data.SaleRecordID = guid; data.Num = item.ProductNum(); data.Price = item.Price(); data.IsDelete = 0; data.CreateBy = $User.UserID; data.UpdateBy = $User.UserID; data.CreateTime = GetNow(); data.UpdateTime = GetNow(); $.ajax({ url: "/api/CommonApi?API=InsertBoxSaleRecord", type: "post", data: { ApiParamObj: JSON.stringify(data) }, dataType: "json", success: function (data) { //console.dir(data); //if (data.Success) { // Alert("添加成功!").on(function () { // self.Refresh(); // $('#dvDialog').modal('hide'); // isS = false; // }) //} } }); } }); } self.save = function () { $("#formDialog").valid(); var arr = self.ProductList(); var guid = Guid(); var o = self.selectedItem(); if ($("#formDialog").valid()) { if (!isS) { isS = true; var data = { SaleRecordID: guid, Amount: self.TotalAmount(), CustomerID: self.selectedItem().CustomerID, Num: self.TotalNum(), IsDelete: 0, CreateBy: $User.UserID, UpdateBy: $User.UserID, CreateTime: GetNow(), UpdateTime: GetNow() }; $.ajax({ url: "/api/CommonApi?API=InsertSale", type: "post", data: { ApiParamObj: JSON.stringify(data) }, dataType: "json", success: function (data) { self.insertRecord(guid); if (data.Success) { Alert("添加成功!").on(function () { self.Refresh(); $('#dvDialog').modal('hide'); isS = false; }) } } }); } } } self.Refresh = function (pageIndex) { //this.pageSize = 10; if (pageIndex == undefined) pageIndex = 1; var data = {}; data.API = "GetSaleList"; data.PageSize = self.pageSize; data.PageIndex = pageIndex; $.ajax({ url: "/api/CommonApi", type: "get", data: data, dataType: "json", success: function (datas) { var list = datas.ApiParamObj; self.SaleList(list); if (list.length == 0) { self.total(0); } else { self.total(list[0].TotalCount); } self.caculatePages(); return datas; } }); } } var vm = new model(); paginationViewModel.call(vm, 0); vm.caculatePages(); vm.goToPage(1); vm.selectedItem(new Product()); ko.applyBindings(vm); //获取客户列表 var getCustomersList = function () { $.getJSON('/api/commonapi?API=GetCustomerUsedCarUse', function (data) { if (data.Success) { vm.customersList(data.ApiParamObj); } }); }; getCustomersList(); });
http://knockout.com.cn/topic/55cf6552829c6622973d7e40