微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MVC 中的 Knockout.js - 无法在 html 表中绑定

如何解决MVC 中的 Knockout.js - 无法在 html 表中绑定

为什么我不能对某些表格标签中的按钮进行点击绑定?如果我将按钮移到表格外它会起作用吗?

<td>
    <div>
        You've clicked <span data-bind="text: numberOfClicks"></span> times
        <button data-bind="click: incrementClickCounter">Click me</button>
    </div>
                                  
</td>

虚拟机:

define(['viewmodels/shell','durandal/services/logger','plugins/dialog','viewmodels/shell','toastr','knockout','kovalidationconfig','plugins/router','typeahead.bundle'],function (shell,logger,dialog,shell,toastr,ko,kvc,router,typeahead) {
        var vm = {
            activate: activate,shell: shell,data: ko.observableArray([]),close: function () {
                $(window).off('popstate',vm.goBack);
                $(window).off('resize',adjustModalPosition);
                dialog.close(vm,'cancel');
            },goBack: function () {
                $(window).off('popstate','back');
            },editPreregisteredChildren: function () {
                router.navigate("#/function/" + this.id);
            },incrementClickCounter : function() {
            var prevIoUsCount = this.numberOfClicks();
            this.numberOfClicks(prevIoUsCount + 1);
        }
            currentPage: ko.observable(1),itemsPerPage: ko.observable(10),hasNextPage: ko.observable(false),prevIoUsPage: prevIoUsPage,nextPage: nextPage,searchCriteria: ko.observable(''),applySearch: applySearch,locations: ko.observableArray([]),locationId: ko.observable(),LocationName: ko.observable(),exportHref: ko.observable("/spa/ExportSchedulings"),bindingComplete: function (view) {
                bindFindLocationEvent(view);
            }
        };
...
)};

解决方法

您是否可能处于嵌套状态?当我绑定到具有多个视图模型的视图时,我有时会遇到这个问题。尝试将 data-bind='with: nameOfTheViewModel' 添加到表数据标记:EG:

<td data-bind='with: nameOfTheViewModel'>
    <div>
        You've clicked <span data-bind="text: numberOfClicks"></span> times
        <button data-bind="click: incrementClickCounter">Click me</button>
    </div>
                                  
</td>

您可能还需要附加 $Parent。 data-bind='with: $Parent.nameOfTheViewModel'

,

您的表的主体可能会遍历一个数组,并且每一行都代表数组项,而不是根虚拟机。您需要绑定到“click: $parent.incrementClickCounter”或“click: $root.incrementClickCounter”。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。