我是knockoutJs的新手,因为我试图通过绑定显示所选的值。但面临重复值的问题。
例如:
{name:" one",price:32.50},{name:" two",price:32.50},
我正试图通过以下代码来实现这一点。
HTML
<select data-bind="options: beforeEventPedersensDropoffCustomerLocation,optionsCaption: 'Please Choose Closest Location',
optionsText: 'name', optionsValue: 'price', value: selectedPricebepdcl" id="before_event_pedersens_dropoff_customer_location_time" ></select>
的js
self.beforeEventPedersensDropoffCustomerLocation = [
{name:"one",price:32.50},
{name:"two",price:32.50},
{name:"three",price:32.50},
{name:"four",price:32.50},
{name:"five",price:32.50},
{name:"six",price:32.50},
{name:"seven",price:0}
];
self.selectedPricebepdcl = ko.observable("");
console.log()
self.beforeEventVal = ko.computed(function() {
if(self.selectedPricebepdcl() !== "")
return ko.utils.arrayFirst(self.beforeEventPedersensDropoffCustomerLocation, function(time) {
return self.selectedPricebepdcl() === time.price;
});
return null;
}, this);
结果
<p data-bind="with: beforeEventVal">
<span data-bind="text: name"></span>
</p>
<p data-bind="with: beforeEventVal">
<span data-bind="text: price"></span>
</p>
任何人都可以帮我这个。
答案 0 :(得分:2)
问题是您已设置optionsValue: 'price'
,因此您选择的项目的唯一信息是价格。然后,您尝试使用它从可用项目中查找所选项目,但您不能这样做,因为它不是唯一标识符。
相反,如果您未指定optionsValue
,则Knockout将使用整个项目作为选择的值。这也让您无需查找所选值,因为您拥有所选的值。
function VM() {
self = this;
self.beforeEventPedersensDropoffCustomerLocation = [{
name: "one",
price: 32.50
},
{
name: "two",
price: 32.50
},
{
name: "three",
price: 32.50
},
{
name: "four",
price: 32.50
},
{
name: "five",
price: 32.50
},
{
name: "six",
price: 32.50
},
{
name: "seven",
price: 0
}
];
self.selectedBepdcl = ko.observable("");
self.selectedName = ko.pureComputed(() => {
const sb = self.selectedBepdcl();
return sb && sb.name ? sb.name : '';
});
}
ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: beforeEventPedersensDropoffCustomerLocation,
optionsCaption: 'Please Choose Closest Location',
optionsText: 'name',
value: selectedBepdcl" id="before_event_pedersens_dropoff_customer_location_time">
</select>
<p data-bind="with: selectedBepdcl">
<span data-bind="text: name"></span>
</p>
<p data-bind="with: selectedBepdcl">
<span data-bind="text: price"></span>
</p>
Pretend this is hidden:
<input data-bind="value: selectedName">