如何在KnockoutJs

时间:2017-03-23 12:42:52

标签: javascript knockout.js

我在代码中使用以下代码

JS

this.packages = [
    {
        sku: "100",
        name: "Fruits",
        description: "its nice",
        locationOptions: [
            { location: "Orange", price: 20, subOptions: [{ quality: "Average", price: 5 }, { quality: "Imported", price: 4 }] },
            { location: "Apple", price: 30, subOptions: [{ quality: "Good", price: 5 }, { quality: "Imported", price: 5 }] },
            { location: "Banana", price: 5, subOptions: [{ quality: "Normal", price: 6 }, { quality: "Imported", price: 3 }] }
        ]
    }
]
this.selectedPackage = ko.observable();
this.selectedLocation = ko.observable();
this.subOptions = ko.observable('0');

我想使用

在Html中显示所选值
<b data-bind="text: name"></b>
<!-- ko with : $parent.selectedLocation -->> <b data-bind="text: location"></b>
<!-- ko with : $parent.subOptions --><b data-bind="text: quality"></b>
<!-- /ko  -->
<!-- /ko  -->

值显示最多二级(水果&gt; Apple ),但第三级值(质量和价格)未显示,可以任何一个请告诉我我在哪里做错了。

1 个答案:

答案 0 :(得分:1)

您似乎在错误的属性级别绑定了对象数据。我已经使用您应该使用的View Model向您展示了以下内容,现在您可以看到所有级别的数据。

let-something="something else"

这样输出如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-debug.js"></script>
<div>
<!-- ko with : $root.selectedPackage -->
<h1 data-bind="text: name"></h1>
    <!-- ko with : $root.selectedLocation -->
    <h2 data-bind="text: location"></h2>
    <div data-bind="foreach: subOptions">   
        <h3 data-bind="text: quality"></h3>
        <h3 data-bind="text: price"></h3>
    </div>
    <!-- /ko  -->
<!-- /ko  -->
</div>

<script>

var ViewModel = function() {
var self = this;
self.packages = [
    {
        sku: "100",
        name: "Fruits",
        description: "its nice",
        locationOptions: [
            { location: "Orange", price: 20, subOptions: [{ quality: "Average", price: 5 }, { quality: "Imported", price: 4 }] },
            { location: "Apple", price: 30, subOptions: [{ quality: "Good", price: 5 }, { quality: "Imported", price: 5 }] },
            { location: "Banana", price: 5, subOptions: [{ quality: "Normal", price: 6 }, { quality: "Imported", price: 3 }] }
        ]
    }
]
self.selectedPackage = ko.observable(self.packages[0]);
self.selectedLocation = ko.observable(self.packages[0].locationOptions[0]);
}

ko.applyBindings(new ViewModel());

</script>