本文介绍了无法解析绑定.击倒错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我学习淘汰赛的第 2 天.

尝试为按钮单击附加deleteItem".它给出了以下错误.

错误

未捕获的错误:无法解析绑定.
消息:ReferenceError:deleteItem 未定义;绑定值:点击:deleteItem

JavaScript:

$(function () {var defaultData = [{编号:1,项目:待办事项1"}, {编号:2,项目:Todo 2"}, {编号:3,项目:Todo 3"}];var viewModel = {listItem: ko.observableArray(defaultData),添加项目:函数(){//添加新项目var id = this.listItem().length + 1;this.listItem.push({身份证:身份证,项目:待办事项"+ id});},删除项目:函数(){警报(这个);}}ko.applyBindings(viewModel, main);});

HTML:

<button data-bind="click: addItem">+ 添加项目</button><div data-bind="foreach: listItem"><input type="text" data-bind="value: item"/><input type="button" data-bind="click: deleteItem"/><br/>

解决方案

deleteItem 函数在你的视图模型上.当您在 foreach 内部进行绑定时,绑定操作的上下文是 listItem 数组中的单个 item.您需要绑定到 $root.deleteItem 以引用根视图模型.

this is my day 2 learning Knockout.

Trying to attach "deleteItem" for button click. it gives the following error.

JavaScript:

$(function () {
    var defaultData = [{
        id: 1,
        item: "Todo 1"
    }, {
        id: 2,
        item: "Todo 2"
    }, {
        id: 3,
        item: "Todo 3"
    }];
    var viewModel = {
        listItem: ko.observableArray(defaultData),
        addItem: function () {
            // Add new item
            var id = this.listItem().length + 1;
            this.listItem.push({
                id: id,
                item: "Todo " + id
            });
        },
        deleteItem: function () {
            alert(this);
        }
    }
    ko.applyBindings(viewModel, main);
});

HTML:

<div id="main">
    <button data-bind="click: addItem">+ Add Item</button>
    <div data-bind="foreach: listItem">
        <input type="text" data-bind="value: item" />
        <input type="button" data-bind="click: deleteItem" />
        <br />
    </div>
</div>
解决方案

The function deleteItem is on your view model. When you're binding inside the foreach, the context of the binding operation is the individual item from the listItem array. You need to bind to $root.deleteItem to reference the root view model.

这篇关于无法解析绑定.击倒错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 19:39