淘汰动态foreach绑定无法正常工作

时间:2015-03-04 23:13:31

标签: javascript html knockout.js


我是淘汰赛的新手。我做了两个div,一个是可见的,一个不是,我想在可见div上单击链接时显示隐藏的div,然后将一个可观察的数组绑定到隐藏div中的无序列表,并显示隐藏的div,其中包含动态值。
HTML:

<div class="visiblediv">
    <ul>
        <li><a data-bind="click: showMenuInfos" href="#">MES INFOS</a>

        </li>
        <li><a data-bind="click: showMenuInter" href="#">DEMANDE</a>

        </li>
        <li><a data-bind="click: showMenuOffres" href="#">OFFRES</a>

        </li>
    </ul>
</div>
<div class="hiddendiv" data-bind="visible: subMenuVisible">
    <ul data-bind="foreach: subMenuItems">
        <li data-bind="text: item"></li>
    </ul>
</div>

JS:

function MenuFunctionVM() {
    self = this;
    self.subMenuVisible = ko.observable(false),
    self.subMenuItems = [],
    self.showMenuInfos = function () {
        this.subMenuVisible(!this.subMenuVisible());
        alert("clicked");
        this.subMenuItems = menuInfos;
    },
    self.showMenuInter = function () {
        this.subMenuVisible(!this.subMenuVisible());
        this.subMenuItems = menuInter;
    },
    self.showMenuOffres = function () {
        this.subMenuVisible(!this.subMenuVisible());
        this.subMenuItems = menuOffres;
    }
};

ko.applyBindings(new MenuFunctionVM());

请帮助:)

1 个答案:

答案 0 :(得分:2)

这是一种方法。它会让你大约75%,你需要添加逻辑来获得你正在寻找的行为。查看JSFiddle了解正常工作的演示<​​/ p>

&#13;
&#13;
function MenuFunctionVM() {
        self = this;
        self.menuItems = [
            {
                name: "MES INFOS",
                items: ["item0", "item1", "item2"]
            },
            {
                name: "DEMANDE",
                items: ["item3", "item4", "item5"]
            },
            {
                name: "OFFRES",
                items: ["item6", "item7", "item8"]
            }
        ];
        self.subMenuVisible = ko.observable(false)
        self.subMenuItems = ko.observableArray([]);
        self.showMenu = function (data) {
            
            self.subMenuVisible(!self.subMenuVisible());
            alert("clicked");
            self.subMenuItems(data.items);
        }
    };
    ko.applyBindings(new MenuFunctionVM());
&#13;
<div class="visiblediv">
    <ul data-bind="foreach: menuItems">
        <li>
            <a data-bind='click: $parent.showMenu,text: $data.name' href='#'></a>        
        </li>
    </ul>
</div>
<div class='hiddendiv' data-bind='visible: subMenuVisible'>
    <ul data-bind='foreach: subMenuItems'>
        <li data-bind='text: $data'></li>
    </ul>
</div>
&#13;
&#13;
&#13;