单击不适用于KnockoutJS

时间:2018-06-24 15:40:32

标签: knockout.js

我是KnockoutJS的新手,下面是我的代码。单击事件没有响应,因为按钮没有响应。有人可以告诉我我要去哪里错了。

我用Google搜索解决方案,但找不到任何帮助。

HTML代码:

<table class="table table-striped b-t text-sm table-bordered table-hover">
        <thead>
          <tr>
            <th>Name</th>
            <th>Mobile</th>
            <th>Role</th>
            <th>Created On</th>
            <th>GM</th>
            <th>Action</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: $data">
          <tr>
            <td data-bind="text: $data.user_fname + ' ' + $data.user_lname">
            </td>
              <button class="btn btn-danger btn-xs" data-bind="click: $data.removeUser">Delete</button>
            </td>
          </tr>
        </tbody>
<script>
  getUsers();
</script>  

JS代码:

function getUsers()
{
 $.ajax({
      url: "api/example/func/format/json",
      dataType: 'json'
 }).done(function(data){
 users = ko.observableArray(data);
 ko.applyBindings(users);
 }).error(function(jqXHR, textStatus){
      alert(jqXHR.status)
 });
}

function removeUser() {
 console.log('userRemoved');
}

1 个答案:

答案 0 :(得分:2)

在下一行ko.applyBindings(users);中,将变量users作为上下文绑定到所有html文档。当您在html中使用$ data时,实际上是该对象users

当您执行foreach(您可以简单地猜测)时,您的上下文就成为users数组中的元素之一。稍后当您调用data-bind="click: $data.removeUser"敲除时,请尝试在当前上下文中找到removeUser对象,即user[i]对象。但这不存在,因为根据您的js-它是在全局得分中定义的

相关问题