以编程方式从 Kendo 网格中选择一行

Selecting a row from a Kendo Grid programmatically

我有一个网格,其中一列是一个带有复选框的模板:

.Name("grid")
.Columns(columns =>
{
    columns.Bound(c => c.Id).ClientTemplate("<input type=\"checkbox\" id=\"chk_#=Id#\" class=\"gridCK\" onclick=\"zzz(this)\"/>");

当我选中复选框时,我希望它的行被选中(反之亦然)。我尝试了以下方法:

function zzz(e) {
    var id = e.id;
    var grid = $("#grid").data("kendoGrid");
    var data = grid.dataSource.data();
    var res = $.grep(data, function (d) {
        if (('chk_' + d.Id) == id) {
            return d.Id;
        }
    });
    var row = grid.table.find('tr[data-id="' + res[0].Id + '"]');
    if (e.checked) {
        row.addClass("k-state-selected");
    } else {
        row.removeClass("k-state-selected");
    }
}

但是没有任何反应,row 变量不是网格的实际行。

我怎样才能做到这一点?

将函数处理程序定义为:

function zzz(e) {
    var row = $(e).closest("tr");
    row.addClass("k-state-selected");
}

查看实际效果:

$(document).ready(function () {
  var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
      dataSource = new kendo.data.DataSource({
        transport: {
          read:  {
            url: crudServiceBaseUrl + "/Products",
            dataType: "jsonp"
          },
          parameterMap: function(options, operation) {
            if (operation !== "read" && options.models) {
              return {models: kendo.stringify(options.models)};
            }
          }
        },
        pageSize: 5,
        schema: {
          model: {
            id: "ProductID",
            fields: {
              ProductID: { editable: false, nullable: true },
              ProductName: { validation: { required: true } },
              UnitPrice: { type: "number", validation: { required: true, min: 1} },
              Discontinued: { type: "boolean" },
              UnitsInStock: { type: "number", validation: { min: 0, required: true } }
            }
          }
        }
      });

  var grid = $("#grid").kendoGrid({
    dataSource: dataSource,
    navigatable: true,
    pageable: true,
    columns: [
      "ProductName",
      { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
      { field: "UnitsInStock", title: "Units In Stock", width: 120 },
      { field: "Select", template: "<input type=\"checkbox\" id=\"chk_#=ProductID#\" class=\"gridCK\" onclick=\"zzz(this)\"/>" }
    ],
    editable: false,
    selectable: "multiple"
  }).data("kendoGrid");
});

function zzz(i) {
  var row = $(i).closest("tr");
  row.addClass("k-state-selected");
}
html {
  font-size: 10px; 
  font-family: Arial, Helvetica, sans-serif; 
}
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1119/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>

<div id="grid"></div>