2

我真的很陌生,我遇到了列表绑定的问题。

   var RequiredItemLine = function () {

            var self = this;
            self.editable = ko.observable(0);
            self.desc = ko.observable();
            self.key = ko.observable();

            self.requireditems = ko.observableArray([
                  { desc: "Boarding of exposed wall openings in the vicinity of ...", key: "233" },
                  { desc: "Call in manufacturers to initiate repairs on ...", key: "242" },
                  { desc: "Call in specialist restorers/recoverers for ...", key: "244" },
                  { desc: "Dispatch items for repair (schedule enclosed)", key: "243" },
                  { desc: "Drying and cleaning of contents comprising ...", key: "240" },
                  { desc: "Drying and protective oiling of water affected equipment", key: "241" },
                  { desc: "Drying out of the affected areas of the premises", key: "235" },
                  { desc: "Removal and repackaging of stock comprising ...", key: "239" },
                  { desc: "Removal of agreed vulnerable contents to a place of safety (schedule enclosed) ", key: "236" },
                  { desc: "Segregation of affected and unaffected stock comprising ...", key: "238" },
                  { desc: "Temporary covering of roof to reinstate water tight integrity ", key: "234" },
                  { desc: "Temporary guarding of affected area", key: "237" },
                  { desc: "Temporary shoring of affected structure", key: "232" }]);

            self.selectedItem = ko.observable(self.requireditems()[0]);



            self.selectedItem.subscribe(function (newValue) {

                var li = "<li>" + newValue.desc + "</li>";

                $('#items').append(li);


            });       
        };


        var RequiredItem = function () {

            var self = this;

            self.requireditemSelection = ko.observableArray([]); // Put one line in by default


            self.requireditemlines = ko.observableArray([]);

            // Operations
            self.addRequiredItem = function () { self.requireditemSelection.push(new RequiredItemLine()) };
            self.RemoveRequiredItem = function (line) { self.requireditemSelection.remove(line) };


        };


        ko.applyBindings(new RequiredItem());

请看这个小提琴。 JSFiddle Link,在页面中包含一个添加选择列表的按钮,每当单击一个按钮时,都会将一个新的选择列表添加到 DOM 中。当用户从选择列表之一中选择项目时,应单独显示所选项目,并且当用户更改已显示在 DOM 中的所选项目时,必须根据选择进行更改,而不是附加新的 li。

在此处输入图像描述

请看第二张图片,我不想显示另一个列表项,而不是我想更改当前添加的项。 在此处输入图像描述

4

1 回答 1

3

我认为你非常接近。我不是 100% 确定我是否正确理解了您的问题,我已将您的问题解释为“想要在只读列表中显示所有选定的项目”。

请参阅更新后的 fiddle,我只是将其更改ul为:

<ul data-bind='foreach: requireditemSelection'>
    <li data-bind="text: selectedItem().desc"></li>
</ul>  

您不需要手动创建li项目并将它们添加到 DOM。只需让 KO 为您处理,数据绑定只读项也是如此。

于 2013-05-09T09:36:24.623 回答