我在使用“ removeCartItem”函数时遇到麻烦。我正在尝试获取“ itemTitle”,以便可以将其发送到服务器以从客户的购物车中删除该项目。但是,“ itemTitle”显示为未定义。
JS
$(function () {
function CartItem() {
var self = this;
self.itemTitle = ko.observable();
self.cartItemID = ko.observable();
self.price = ko.observable();
self.qty = ko.observable();
self.img = ko.observable();
self.lineTotal = ko.observable();
}
function viewModel(cartData) {
var self = this;
self.cartItems = ko.observableArray([]);
self.addItemToCart = function (listingID, qty) {
$.ajax({
url: '@Url.Action("phoneAdd","ShoppingCart",null)',
type: 'POST',
data: { 'listingID': listingID, 'requestedQty': qty },
success: function (data) {
alert(data.status);
}
});
};
self.removeCartItem = function (CartItem) {
alert(CartItem.price);
};
self.loadCartData = function () {
$.getJSON('@Url.Action("koShoppingCartItems","ShoppingCart",null)', function (data) {
$.each(data, function () {
alert(data);
self.cartItems.push({
itemTitle: ko.observable(this.itemTitle),
price: ko.observable(this.Price),
qty: ko.observable(this.Quantity),
lineTotal: ko.observable(this.lineTotal)
});
});
});
}
self.loadCartData();
}
ko.applyBindings(new viewModel());
});
的HTML
<a href='#' data-bind='click: $parent.removeCartItem'>Remove</a>
最佳答案
也许这个样机可以帮助您了解问题出在哪里。您没有包含任何HTML,因此我们看不到您的绑定是否有问题。我注意到您实际上并没有在代码顶部使用CartItem构造函数。 removeCartItem
方法采用一个具有相同名称的参数,这有点令人困惑。通常,首字母大写表示构造函数。
$(function() {
function viewModel(cartData) {
var self = this;
self.cartItems = ko.observableArray([]);
self.addItemToCart = function(listingID, qty) {
$.ajax({
url: '@Url.Action("phoneAdd","ShoppingCart",null)',
type: 'POST',
data: {
'listingID': listingID,
'requestedQty': qty
},
success: function(data) {
alert(data.status);
}
});
};
self.removeCartItem = function(CartItem) {
alert(CartItem.itemTitle());
};
self.loadCartData = function() {
//$.getJSON('@Url.Action("koShoppingCartItems","ShoppingCart",null)', function(data) {
var data = [{
itemTitle: 'One',
Price: '1',
Quantity: '1',
lineTotal: '1'
}, {
itemTitle: 'Two',
Price: '2',
Quantity: '2',
lineTotal: '4'
}
];
$.each(data, function() {
//alert(data);
self.cartItems.push({
itemTitle: ko.observable(this.itemTitle),
price: ko.observable(this.Price),
qty: ko.observable(this.Quantity),
lineTotal: ko.observable(this.lineTotal)
});
});
//});
}
self.loadCartData();
}
ko.applyBindings(new viewModel());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach:cartItems">
<span data-bind="text:itemTitle"></span>
<button data-bind="click:$root.removeCartItem">Remove</button>
</div>