knockout.js 在 MVC 中 - 在 html table 中无法绑定

knockout.js in MVC - not working binding in html table

为什么有些table的标签中的按钮不能点击绑定?如果我将按钮移到 table 之外,它会起作用吗?

<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', vm.goBack);
                $(window).off('resize', adjustModalPosition);
                dialog.close(vm, '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' 添加到 table 数据标签: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。数据绑定='with: $Parent.nameOfTheViewModel'

您 table 的正文可能遍历数组,每一行代表数组项,而不是根虚拟机。您需要绑定到“点击:$parent.incrementClickCounter”或“点击:$root.incrementClickCounter”。