【问题标题】:JS passing the forEach variable to the lookup functionJS 将 forEach 变量传递给查找函数
【发布时间】:2021-05-27 23:28:23
【问题描述】:

请帮助我了解如何将此参数传递给formatter 的查找函数。我尝试为制表符动态创建表格行:

有效

keys = ["name", "price", "number"];
doAjax().then( variable => { 
    if ( products ) {
        let cols = [{title: "number", field: "number"}];
        keys.forEach(function ( key ) {
            let formatter = "";

            // check if key is number
            if ( key == "number" ) {
                formatter = function( cell ) {
                                return `<div íd="${key}">${cell.getValue()}</div>`;
                            };
            };
            cols.push({title: key, field: "data." + key, formatter: formatter});
         });
    };
 });    

不起作用

let testf = function( cell, key ) { 
    return `<div íd="${key}">${cell.getValue()}</div>`; // key is not accessible here
};

keys = ["name", "price", "number"];
doAjax().then( variable => { 
    if ( products !== null ) {
        let cols = [{title: "number", field: "number"}];
        keys.forEach(function ( key ) {
            let formatter = "";

            // check if key is number
            if ( key == "number" ) {
                formatter = testf(cell, key);  // not working
            };
            cols.push({title: key, field: "data." + key, formatter: formatter});
         });
    };
 });    

上下文代码

var table = new Tabulator("#products", {
    ajaxURL: "api/products",
    columns: cols,
});

我如何重写第二种方法,让它传递参数键?

【问题讨论】:

    标签: javascript tabulator


    【解决方案1】:

    创建一个将初始 cell 作为参数的函数,并使用它和 key 调用 testf

    if (key == "number") {
        formatter = cell => testf(cell, key);
    };
    

    【讨论】:

    • 这是我在 works 方法中所写内容的简短版本,对吧?完全一样,只是符号不同?你能详细说明吗(它有效,我只是想了解更多)。
    • formatter 需要是一个接受 cell 作为参数的函数,并返回一个 HTML 字符串。它只接受一个cell 参数——它对key 一无所知,因此需要在外部范围内定义key。因此,在处理程序内部,testf(cell, key) 将能够使用单元格(来自参数)和键(来自外部范围)调用函数。
    【解决方案2】:

    只需将 key 作为第一个参数,然后绑定它:

    let testf = function( key, cell ) { 
        return `<div íd="${key}">${cell.getValue()}</div>`; 
    }
    
    formatter = testf.bind(key);
    

    【讨论】:

    • 我不得不将let testf = function( key, cell ) 切换到let testf = function( cell, key )。现在cell 是正确的,但是key 是空的?试过:formatter = testf.bind(key);let testf = function( key, cell ) { console.log( key, '|', cell ) }; 我进入控制台:{} | [object Object] //correct
    猜你喜欢
    • 2010-09-09
    • 2021-02-10
    • 2012-08-20
    • 2020-10-23
    • 1970-01-01
    • 2018-11-30
    • 2020-07-28
    相关资源
    最近更新 更多