You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Kendo UI在网格顶部添加新行?

Kendo UI网格:让新记录始终显示在首行的解决方案

Hey,我来帮你搞定这个问题~你说点击「Add New Record」按钮添加单条记录时没问题,但连续加多条的话新行会不断下移,想要每次新增的记录都固定在网格最顶部,对吧?

先看看你当前的网格配置代码:

<div id="commentsDiv" style="width: 100%; margin-bottom:15px; border: 0px;">
  <div data-role="grid" data-scrollable="true" data-resizable="true" data-editable="inline" data-toolbar="['create', 'cancel']" data-columns="[ { field: 'cmntTxt', title: 'Comment', width: 400}, { field: 'createdDate' , title: 'Created On', width: 125, type : 'date', 'format' : '{0: MM/dd/yyyy HH:mm:ss}'}, { command: ['edit', 'destroy',], title: 'Actions', width: 150 } ]" data-bind="source: commentsDS" data-scrollable='true' data-sortable='true' data-filterable='true' data-pageable="{ pageSize: 15, pageSizes: [15, 50, 100, 200, 500], refresh : true, buttonCount : 5 }" style="width: 100%; height: 500px">
  </div>
</div>

再结合你提供的addRow函数代码来看,问题出在新记录的插入位置逻辑上——默认情况下,它会根据当前视图的第一条数据来确定插入点,连续添加时这个位置会跟着下移。下面给你两个简单的解决方案:


方案一:直接配置网格的createAt属性(最推荐)

Kendo UI网格的editable配置里自带了createAt参数,专门用来控制新记录的插入位置。你只需要把原来的data-editable="inline"改成带createAt: "top"的JSON配置就行:

修改后的data-editable属性:

data-editable='{"inline": true, "createAt": "top"}'

完整的网格配置代码如下:

<div id="commentsDiv" style="width: 100%; margin-bottom:15px; border: 0px;">
  <div data-role="grid" 
       data-scrollable="true" 
       data-resizable="true" 
       data-editable='{"inline": true, "createAt": "top"}' 
       data-toolbar="['create', 'cancel']" 
       data-columns="[ 
         { field: 'cmntTxt', title: 'Comment', width: 400}, 
         { field: 'createdDate' , title: 'Created On', width: 125, type : 'date', 'format' : '{0: MM/dd/yyyy HH:mm:ss}'}, 
         { command: ['edit', 'destroy'], title: 'Actions', width: 150 } 
       ]" 
       data-bind="source: commentsDS" 
       data-scrollable='true' 
       data-sortable='true' 
       data-filterable='true' 
       data-pageable="{ pageSize: 15, pageSizes: [15, 50, 100, 200, 500], refresh : true, buttonCount : 5 }" 
       style="width: 100%; height: 500px">
  </div>
</div>

这个配置会告诉网格,每次创建新记录时直接插入到数据源的最顶端,自然就会显示在网格第一行啦。


方案二:手动修改addRow函数逻辑(如果方案一不生效)

要是因为Kendo UI版本或者其他原因,createAt配置没起作用,那我们直接修改addRow里的插入位置逻辑就行。找到你提供的addRow函数里这段代码:

e = s.indexOf(u[0]), 'bottom' == c.toLowerCase() && (e += u.length, d && !s.options.serverPaging && u.length >= d && (e -= 1))

把它替换成:

e = 0; // 强制将新记录插入到数据源的第一个位置

这样不管之前有没有添加过记录,新记录都会被插入到索引0的位置,肯定会显示在网格最顶部。


额外提醒

如果你的网格开启了排序(比如按createdDate正序),可能会把新记录排到后面。这时候你可以:

  • 把排序规则改成倒序(让最新的记录排在最前面)
  • 在添加新记录时,给createdDate设置一个比现有所有记录都晚的时间
  • 或者暂时禁用排序(不过看你开了data-sortable='true',这个可能不太适用)

内容的提问来源于stack exchange,提问作者Saritha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:34:02