【问题标题】:How can I display a menu item's contents without clicking on the item如何在不单击项目的情况下显示菜单项的内容
【发布时间】:2021-07-22 04:34:41
【问题描述】:

我想显示第一个菜单项的内容,而不单击它,使其成为打开应用程序时显示的默认内容。我已经尝试了我能想到的一切。 Console.log 显示可观察到的“selectedView”的值类似于“View {title:“Event List”,templateName:“EventList”}”,所以我尝试将其设置为该值,但它仍然有效。

<div class="inServMenu" data-bind="foreach: views">
    <a href="#" class="inServMenuItem" data-bind="text: title, click: $root.selectedView"></a>
</div>

<div data-bind="with: selectedView">
    <div data-bind="template: { name: templateName }"></div>
</div>

<script id="EventList" type="text/html">
 <span>"Here's the Event List..."</span>
</script>

<script id="RosterList" type="text/html">
 <span>"Here's the Roster List..."</span>
</script> var View = function (title, templateName) {
    this.title = title;
    this.templateName = templateName;
};

// VIEWMODEL
var viewModel = {
    selectedView: ko.observable(),
    views: ko.observableArray([
        new View('Event List', 'EventList'),
        new View('Roster List', 'RosterList')
    ]),
}

ko.applyBindings(viewModel);```

[Here's a jsfiddle][1]


  [1]: http://jsfiddle.net/jjfrick/hmfubkcr/18/

【问题讨论】:

    标签: templates knockout.js menu


    【解决方案1】:

    您需要稍微更改您的视图模型构造函数,以便您可以引用它:

    function ViewModel () {
        var vm = this;
        vm.views = ko.observableArray([
            new View('Event List', 'EventList'),
            new View('Roster List', 'RosterList')
        ]);
        vm.selectedView = ko.observable(vm.views()[0])
    }
    
    ko.applyBindings(new ViewModel());
    

    【讨论】:

    • 谢谢伍德罗弟兄。我一直使用“var viewModel”方法与函数,但看起来我的方法有其局限性。你觉得这是真的吗?
    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 2021-04-18
    • 2014-04-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多