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

Layui项目CASES场景下options1.where赋值报错Uncaught TypeError求解决方案

报错原因
  • 条件声明变量未赋值:你在if分支内用var声明options1和options,由于var存在变量提升特性,无论分支是否执行,变量都会被提升到当前函数作用域声明,但如果对应分支首次加载时没有触发,变量不会被赋值,值为undefined。比如首次加载displayUnit不为CASES,则options1全程为undefined,后续搜索切换为CASES时,执行options1.where = data.field自然会抛出找不到属性的错误。
  • 未适配displayUnit切换场景:代码默认首次加载的displayUnit取值和搜索时一致,若用户在页面加载后切换了displayUnit的选项,搜索时用到的配置还是首次加载生成的,要么不存在要么和当前取值不匹配。
  • 事件重复绑定缺陷:你把table.on('tool')表格工具条事件的绑定逻辑写在搜索提交的回调里,每次点击搜索都会重复绑定一次事件,触发时会执行多次跳转逻辑。
  • 冗余代码问题:两份表格配置仅列配置cols有差异,其余公共配置完全重复,增加维护成本的同时也提高了变量出错概率。
修复方案

先抽离公共配置,封装动态生成配置的函数,将事件绑定、工具函数移到全局作用域,搜索时根据当前displayUnit取值动态处理配置,修改后完整代码如下:

layui.use(['form', 'element', 'laydate', 'jquery', 'layer', 'table'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        searchDate = '',
        // 顶部统一声明配置变量,抽离公共配置
        tableCommonConfig = {
            elem: '#resultMonitoringTable',
            id: 'resultMonitoring',
            limit: Number.MAX_VALUE,
            page: false,
            loading: true,
            method: 'GET',
            url: '../../collection/resultMonitoringData',
            response: {
                statusName: 'code',
                dataName: 'data',
                statusCode: 200,
                msgName: 'message',
                countName: 'totalCount'
            },
            done: function(res) {
                data = res.data;
                console.log("result: " + data);
            }
        },
        // 通用列配置,公共列抽离
        commonCols = [
            {
                title: 'Select',
                width: '10%',
                align: 'center',
                toolbar: '#orderListBar'
            },
            {
                field: 'delinquency',
                title: 'Delinquency',
                width: '15%',
                align: 'center',
                templet: function(s) {
                    var delinquency = s.delinquency;
                    switch(delinquency) {
                        case '0': return 'M1';
                        case '1': return 'M2';
                        case '2': return 'M3';
                        case '3': return 'M4';
                        case '4': return 'M5';
                        case '5': return 'M6';
                        case '6': return 'M7';
                        default: return '>=M8';
                    }
                }
            }
        ];
    var laydate = layui.laydate;
    laydate.render({
        elem: '#reportDate', 
        lang: 'en',
        done: function (value) {
            console.log(value); 
            searchDate = value;
        }
    });

    // 封装:根据displayUnit生成对应表格配置
    function getTableConfig(displayUnit) {
        var config = JSON.parse(JSON.stringify(tableCommonConfig));
        if (displayUnit == "CASES") {
            config.cols = [[
                ...commonCols,
                {
                    field: 'cases',
                    title: 'Cases',
                    width: '20%',
                    align: 'center',
                    templet: function(s) {
                        return s.cases;
                    }
                },
                {
                    field: 'billing',
                    hide: true,
                    templet: function(s) {
                        return formatMoney(s.billing);
                    }
                },
                {
                    field: 'collection',
                    title: 'Collected',
                    width: '20%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney(s.collection);
                    }
                },
                {
                    field: 'balance',
                    title: 'Balance',
                    width: '20%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney(s.billing - s.collection);
                    }
                },
                {
                    field: 'pct',
                    title: 'Pct%',
                    width: '15%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney((s.collection / s.billing) * 100) + '%';
                    }
                }
            ]];
        } else {
            config.cols = [[
                ...commonCols,
                {
                    field: 'billing',
                    title: 'Billing',
                    width: '20%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney(s.billing);
                    }
                },
                {
                    field: 'collection',
                    title: 'Collected',
                    width: '20%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney(s.collection);
                    }
                },
                {
                    field: 'balance',
                    title: 'Balance',
                    width: '20%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney(s.billing - s.collection);
                    }
                },
                {
                    field: 'pct',
                    title: 'Pct%',
                    width: '15%',
                    align: 'center',
                    templet: function(s) {
                        return formatMoney((s.collection / s.billing) * 100) + '%';
                    }
                }
            ]];
        }
        return config;
    }

    // 首次加载渲染
    var initDisplayUnit = $('[name=displayUnit]').val();
    console.log("a" + initDisplayUnit);
    var initConfig = getTableConfig(initDisplayUnit);
    table.render(initConfig);

    // 搜索提交事件
    form.on('submit(search)', function(data) {
        if (searchDate.length === 0) {
            layer.msg('Report Date can\'t be empty!', {
                icon: 2
            });
            return false; // 阻止空日期提交
        }
        var currentDisplayUnit = $('[name=displayUnit]').val();
        var currentConfig = getTableConfig(currentDisplayUnit);
        currentConfig.where = data.field;
        table.reload('resultMonitoring', currentConfig);
        return false;
    });

    // 表格工具条事件绑定移到全局,避免重复绑定
    table.on('tool(resultMonitoringTable)', function (obj) {
        var data = obj.data; 
        var layEvent = obj.event; 
        var reportDate = $('[name=reportDate]').val();
        var displayUnit = $('[name=displayUnit]').val();
        console.log("report date and display unit" +reportDate+displayUnit);
        if (layEvent == "view") {
            console.log("view: " + data.delinquency + reportDate);
            location.href = '/collection/view?delinquency='+ data.delinquency+'&reportDate='+data.reportDate+'&displayUnit='+data.displayUnit;
        }
    });

    // 工具函数移到全局
    function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
        try {
            decimalCount = Math.abs(decimalCount);
            decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
            const negativeSign = amount < 0 ? "-" : "";
            let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
            let j = (i.length > 3) ? i.length % 3 : 0;
            return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
        } catch (e) {
            console.log(e)
        }
    };
});

另外你原来代码里列配置的field: 'billing' && 'collection'写法存在逻辑问题,&&运算符返回最后一个真值,等价于直接写field: 'collection',上述修复代码已经改成了语义化的字段名,不影响原有功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:15:03