Javascript jQuery和KnockOutJS将滑块链接到购物车示例
使用KnockOutJS.com中的购物车示例-如何链接滑块(或滑块数量),以便总值考虑下拉列表以及在滑块控件中选择的其他项目(本例中为太阳镜)的数量 我已经得到了调用getExtrasTotal()函数的总值——当下拉列表或项目数发生变化时——但当滑块发生变化时却没有 这里有一把小提琴: HTML: 谢谢,Javascript jQuery和KnockOutJS将滑块链接到购物车示例,javascript,jquery,jquery-mobile,knockout.js,Javascript,Jquery,Jquery Mobile,Knockout.js,使用KnockOutJS.com中的购物车示例-如何链接滑块(或滑块数量),以便总值考虑下拉列表以及在滑块控件中选择的其他项目(本例中为太阳镜)的数量 我已经得到了调用getExtrasTotal()函数的总值——当下拉列表或项目数发生变化时——但当滑块发生变化时却没有 这里有一把小提琴: HTML: 谢谢, 标记首先,您需要确保滑块也更新了一个ko.observable 然后,extrasTotal也需要是一个ko.computed,就像grandTotal,但要观察额外的而不是购物车的线条
标记首先,您需要确保滑块也更新了一个
ko.observable
然后,extrasTotal
也需要是一个ko.computed
,就像grandTotal
,但要观察额外的而不是购物车的线条
用一些又快又脏的:
<input type="range" class="slide" name="slider1" id="slider1" min="0" max="10" data-bind="value: sunglasses">
当然,在现实中,您可能希望将其制作成一个可能的附加数组,并使用foreach
呈现:s,然后从数据库中获取价格
:
谢谢@dan-p-一个更优雅的解决方案!干杯,马克
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
var CartLine = function() {
var self = this;
self.category = ko.observable();
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function() {
return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});
// Whenever the category changes, reset the product selection
self.category.subscribe(function() {
self.product(undefined);
});
};
var Cart = function() {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.grandTotal = ko.computed(function() {
var total = 0;
$.each(self.lines(), function() { total += this.subtotal() })
var
return total;
});
// Operations
self.addLine = function() { self.lines.push(new CartLine()) };
self.removeLine = function(line) { self.lines.remove(line) };
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
productName: line.product().name,
quantity: line.quantity()
} : undefined
});
alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
};
function getExtrasTotal() {
var extrastotal = 0;
var count = 0;
var arr = [];
$('.slide')
.each(function (index, Element) {
var obj = {
id: $(Element).data("id"),
price: $(Element).data("price"),
number: $(Element)
.val()
};
extrastotal += obj.number * obj.price;
});
return extrastotal;
}
ko.applyBindings(new Cart());
<input type="range" class="slide" name="slider1" id="slider1" min="0" max="10" data-bind="value: sunglasses">
self.extrasTotal = ko.computed(function() {
var sunglasses = self.sunglasses();
var docholders = self.docholders();
return sunglasses * self.sunglassPrice + docholders * self.docholderPrice;
});
self.extrasTotal = ko.computed(function() {
var total = 0;
ko.utils.arrayForEach(self.extras(), function (extra) {
var count = extra.count();
total = total + (count * extra.price);
});
return total;
});