javascript 在knockout.js 中嵌套foreach

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10922468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:28:56  来源:igfitidea点击:

Nested foreach in knockout.js

javascriptforeachknockout.js

提问by mat-mcloughlin

I can't seem to get a nested foreach to work.

我似乎无法让嵌套的 foreach 工作。

JS code is:

JS代码是:

$(document).ready(function() {

    function chartValueViewModel(date, price) {
        this.date = date;
        this.price = price;
    }

    function chartViewModel(id, name, lineType, values) {
        this.id = id;
        this.name = name;
        this.lineType = lineType;
        this.values = ko.observableArray(values);
    }

    function liveCurveViewModel() {

        this.chartsData = ko.observableArray([]);
        var chartsData = this.chartsData;

        this.init = function() {

            var mappedCharts = $.map(chartValues,
            function(chart) {
                var mappedValues = $.map(chart.chartValues, function(value) {
                    return new chartValueViewModel(value.dateTime, value.price);
                })
                return new chartViewModel(chart.id, chart.name, chart.liveCurveTypeId, mappedValues);
            });

            chartsData(mappedCharts);
        };
    }

    var vm = new liveCurveViewModel();
    vm.init();
    ko.applyBindings(vm);

});

Html is:

html是:

<ul data-bind="foreach: chartsData ">
    <li data-bind="text: name">
        <ul data-bind="foreach: values">
           <li data-bind="text: price">
           </li>
        </ul>
    </li>
</ul>

The outside loop renders correctly, but I get nothing from the inside loop, not even an error message. I've checked and the values field on the chartViewModel is populated.

外部循环正确呈现,但我从内部循环中什么也没得到,甚至没有错误消息。我已经检查并填充了 chartViewModel 上的值字段。

回答by RP Niemeyer

The textbinding that you have on your outside liis overwriting the content inside of it, so it is blowing away your inner foreach. The textbinding sets the innerText/textContent of the element, which overwrites the current children.

text你在外面的绑定li覆盖了里面的内容,所以它吹走了你的内心foreach。的text结合集元素的innerText /的textContent,其覆盖当前的儿童。

You would want to do something like:

你会想要做这样的事情:

<ul data-bind="foreach: chartsData ">
    <li>
        <span data-bind="text: name"></span>
        <ul data-bind="foreach: values">
           <li data-bind="text: price">
           </li>
        </ul>
    </li>
</ul>