我有使用 Kendo UI 输出的表格,如下所示:
我想要的结果是让表格有一个额外的列“#”,它只包含数据 1、2、3、4 等。
下面是我解决这个问题的尝试,但它不起作用,即正如您在图像中看到的那样,“#”列是空白的:(使用模板列和 DataBound 事件)
@(
Html.Kendo().Grid(Model.CryptoViewModel.data)
.Name("Crypto")
.Columns(columns =>
{
columns.Template("<span class='row-number'></span>").Title("#");
columns.Bound(x => x.name).Title("Name")
.HeaderHtmlAttributes(new { @class = "crypto-header" }).HtmlAttributes(new { @class = "k-text-left" });
columns.Bound(x => x.symbol).Title("Symbol")
.HeaderHtmlAttributes(new { @class = "crypto-header" }).HtmlAttributes(new { @class = "k-text-left" });
columns.Bound(x => x.quote.USD.price).Title("Price").Format("{0:c2}")
.HeaderHtmlAttributes(new { @class = "crypto-header" }).HtmlAttributes(new { @class = "k-text-left" });
columns.Bound(x => x.circulating_supply).Title("Circulating Supply").Format("{0:n0}")
.HeaderHtmlAttributes(new { @class = "crypto-header" }).HtmlAttributes(new { @class = "k-text-left" });
columns.Bound(x => x.max_supply).Title("Max Supply").Format("{0:n0}")
.HeaderHtmlAttributes(new { @class = "crypto-header" }).HtmlAttributes(new { @class = "k-text-left" });
columns.Bound(x => x.last_updated).Title("Last Updated").Width(200)
.HeaderHtmlAttributes(new { @class = "crypto-header" }).HtmlAttributes(new { @class = "k-text-left" });
})
.Editable()
.Filterable()
.Sortable()
.Events(ev => ev.DataBound("onDataBinding"))
)
<script>
function onDataBinding() {
var grid = $("#Crypto").data("kendoGrid");
var dataSource = grid.dataSource;
var i = 1;
$(dataSource._data).each(function () {
$('table tr').find('td:first').html(i);
//var rowLabel = grid.find(".row-number");
//$(rowLabel).html(i)
i++;
});
}
解决这个问题我缺少什么?
试图直接更改小部件的 html 是一个很大的错误。永远不要那样做。小部件经常动态呈现 html,因此您的更改将被覆盖。
dataBinding
事件接收第一个参数中的数据项,因此您可以在它们在网格中使用之前更改它们:
function onDataBinding(e) {
e.items.forEach((item, index) => item.row_counter = (index + 1));
}
演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/themes/6.2.0/default/default-ocean-blue.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2023.1.314/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2023.1.314/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2023.1.314/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script>
$('#grid').kendoGrid({
dataSource: new kendo.data.DataSource({
data: [{
name: 'John'
},{
name: 'Jane'
}]
}),
columns: [{
field: 'row_counter'
},{
field: 'name'
}],
dataBinding: function(e) {
e.items.forEach((item, index) => item.row_counter = (index + 1));
}
});
</script>
</body>
</html>