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

JsGrid设置date字段页面加载失败,自定义字段后字段消失求助

解决JsGrid自定义Date字段后字段消失的问题

问题原因

  1. 自定义MyDateField未设置默认宽度,导致字段被压缩至不可见
  2. insertValue/editValue错误调用useCurrent()(该方法用于设置当前时间,而非获取选中值)
  3. 未处理空日期或无效日期,引发渲染异常
  4. 缺少datetimepicker依赖库(moment.js、datetimepicker的CSS/JS)

修复方案

1. 引入依赖库

确保本地已引入以下文件,并在js.js之前加载:

  • moment.js
  • bootstrap-datetimepicker的CSS文件
  • bootstrap-datetimepicker的JS文件

2. 修正自定义Date字段代码

替换原有MyDateField的实现:

var MyDateField = function(config) {
    jsGrid.Field.call(this, config);
};

// 正确继承jsGrid.Field
MyDateField.prototype = Object.create(jsGrid.Field.prototype);
MyDateField.prototype.constructor = MyDateField;

// 初始化时设置默认宽度,避免字段消失
MyDateField.prototype.init = function() {
    this.width = this.width || 120;
    jsGrid.Field.prototype.init.call(this);
};

// 处理空值的排序逻辑
MyDateField.prototype.sorter = function(date1, date2) {
    const d1 = date1 ? new Date(date1) : null;
    const d2 = date2 ? new Date(date2) : null;
    if (!d1 && !d2) return 0;
    if (!d1) return -1;
    if (!d2) return 1;
    return d1 - d2;
};

// 渲染列表时处理空值和无效日期
MyDateField.prototype.itemTemplate = function(value) {
    if (!value) return "";
    const date = new Date(value);
    return isNaN(date.getTime()) ? "" : date.toLocaleDateString();
};

// 插入模板:初始化日期选择器
MyDateField.prototype.insertTemplate = function(value) {
    this._insertPicker = $("<input class='date-picker' type='text'>");
    this._insertPicker.datetimepicker({ format: 'YYYY-MM-DD' });
    return this._insertPicker;
};

// 编辑模板:回显已有日期
MyDateField.prototype.editTemplate = function(value) {
    this._editPicker = $("<input class='date-picker' type='text'>");
    this._editPicker.datetimepicker({ format: 'YYYY-MM-DD' });
    if (value) {
        const date = new Date(value);
        if (!isNaN(date.getTime())) {
            this._editPicker.data("DateTimePicker").date(date);
        }
    }
    return this._editPicker;
};

// 获取插入时的日期值
MyDateField.prototype.insertValue = function() {
    const picker = this._insertPicker.data("DateTimePicker");
    return picker ? picker.date().format('YYYY-MM-DD') : null;
};

// 获取编辑时的日期值
MyDateField.prototype.editValue = function() {
    const picker = this._editPicker.data("DateTimePicker");
    return picker ? picker.date().format('YYYY-MM-DD') : null;
};

jsGrid.fields.date = MyDateField;

3. 完善字段配置

在fields数组中为date字段显式设置宽度(可选,但更稳妥):

{
    title:"Load Date",
    name: "loaddate", 
    type: "date",
    width: 150
}

4. 后端数据格式校验

确保fetch_data.php返回的loaddate字段为合法日期字符串(如YYYY-MM-DD),避免前端解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:00:59