我在这里有一些代码,我试图根据数据项的值设置单元格的背景颜色:
http://dojo.telerik.com/@solidus-flux/eHaMu
<!DOCTYPE html> <html> <head> <Meta charset="utf-8"> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.common.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.rtl.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.default.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.default.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.mobile.all.min.css"> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://cdn.kendostatic.com/2014.3.1411/js/kendo.all.min.js"></script> </head> <body> <div id="grid"></div> <script> $("#grid").kendoGrid({ columns: [ { field: "name",title: "Name",attributes: function(e) { return { "class": "table-cell",style: e.name == "Jane Doe" ? "background-color: red" : "background-color: green" }; } //attributes: { //"class": "table-cell",//style: "text-align: right; font-size: 14px" //} } ],dataSource: [ { name: "Jane Doe" },{ name: "John Doe" }] }); </script> </body> </html>
我意识到我可以使用模板执行此操作,但这需要额外的html元素,因为您无法更改td本身的标记.如果支持,我想使用函数返回属性.
解决方法
你说你不想使用模板,但我认为你在谈论列模板.
您可以使用行模板更改td本身的标记:
<script id="template" type="text/x-kendo-template"> <tr data-uid="#= uid #"> # this.columns.forEach(function(col) { var val = data[col.field],css,style = '' cClasses = ''; if (typeof col.attributes === 'function') { css = col.attributes(data); cClasses = css["class"]; style = css.style } # <td class='#= cClasses #' style='#= style #'> #= data[col.field] # </td> # }) # </tr> </script>
要使循环起作用,您需要将模板绑定到网格:
var grid = $("#grid").kendoGrid({ columns: [{ field: "name",attributes: function (e) { return { "class": "table-cell",style: e.name == "Jane Doe" ? "background-color: red" : "background-color: green" }; } },{ field: "title",title: "Title" }],dataSource: [{name: "Jane Doe",title: "Dr. Dr."},{name: "John Doe",title: "Senior Citizen"}] }).data("kendoGrid"); var template = kendo.template($("#template").html()).bind(grid); grid.setOptions({ rowTemplate: template });
(demo)
作为替代方案,您还可以创建如下属性:
{ field: "name",attributes: { "class": "# if(data.name === 'Jane Doe') { # red # } else { # green # } #" } },
这将具有不使用行模板的优点,但您必须使用逻辑的模板语法.
(demo)