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

Kendo for jQuery 表格列逐行动态渲染下拉框或文本输入框实现问题

实现方案

要实现Kendo Grid单列按行数据动态切换编辑控件,核心是使用Grid列的editor自定义配置,结合列模板template完成非编辑态的适配,具体改动如下:

1. 修改目标列配置

给Expense Type列新增自定义编辑函数配置,替换原有全列统一控件的逻辑:

{
    field: "cost_type_description",
    title: "费用类型",
    template: columnTemplateFunction,
    // 新增自定义编辑控件渲染入口
    editor: dynamicControlEditor,
    filterable: {
        operators: {
            string: {
                contains: "包含",
                eq: "等于",
                neq: "不等于"
            }
        }
    }
},

2. 实现动态控件渲染函数

该函数可以拿到当前行的完整数据,你可以根据任意字段的取值判断渲染下拉框还是文本输入框:

// 动态编辑控件渲染函数
function dynamicControlEditor(container, options) {
    const currentRowData = options.model;
    // 此处可以替换为你实际的判断逻辑,比如根据费用金额、客户类型等字段判断
    // 示例逻辑:如果当前行的narrative字段包含「固定分类」标识,就渲染下拉选择,否则用文本输入
    if (currentRowData.narrative && currentRowData.narrative.indexOf("固定分类") !== -1) {
        // 渲染下拉框
        $('<input name="' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                dataSource: ddlDataSource,
                dataTextField: "displayValue",
                dataValueField: "value",
                value: options.model.cost_type_description
            });
    } else {
        // 渲染文本输入框
        $('<input type="text" class="k-input k-textbox" name="' + options.field + '"/>')
            .appendTo(container);
    }
}

3. 适配非编辑态的列模板

修改原有columnTemplateFunction,保证非编辑状态下的显示内容和控件类型匹配:

function columnTemplateFunction(dataItem) {
    // 编辑逻辑保持一致的判断规则
    if (dataItem.narrative && dataItem.narrative.indexOf("固定分类") !== -1) {
        // 下拉类型的话匹配显示文本而不是存的value值
        const matchedOption = ddlDataSource.find(item => item.value == dataItem.cost_type_description);
        return matchedOption ? kendo.htmlEncode(matchedOption.displayValue) : "";
    }
    // 文本类型直接输出内容
    return kendo.htmlEncode(dataItem.cost_type_description || "");
}

4. 修正原有代码的错误点

  • 删除DataSource里重复定义的sort配置
  • 删除Grid配置里重复定义的schema配置,数据源已经定义过模型无需重复配置
  • 原有dataBound里的下拉框初始化逻辑可以删除,自定义editor已经接管编辑态控件渲染
  • 原有onDDLChange里的Grid选择器错误,将$("#grid")修改为$("#pending")和你实际定义的Grid ID匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:15:03