【问题标题】:Have input field show blank Instead of [object Object] or {让输入字段显示空白而不是 [object Object] 或 {
【发布时间】:2020-05-29 06:32:55
【问题描述】:

使用 jquery 数据表 - 如何让我的输入显示为空

data: null,
name: "MillerLite",
render: function (data, type, row) {
    if (type === 'display') {
        return '<input name="MillerLite" value="' + data.toString() + '" />';
    }
    return data;
}

我试过了 - 但这显示 [null Null]

data: null,
name: "MillerLite",
render: function (data, type, row) {
    if (type === 'display') {
        return '<input name="MillerLite" value="' + data.toString() + '" />';
    }
    return data;
}

还有 - 但默认情况下会显示左括号 {

data: null,
name: "MillerLite",
render: function (data, type, row) {
    if (type === 'display') {
        return '<input name="MillerLite" value="' + JSON.stringify(data) + '" />';
    }
    return JSON.stringify(data);
}

【问题讨论】:

  • 如果我删除 .tostring() 它显示 [object Object]
  • data 是表示当前行数据的对象。您需要访问该对象的属性以填充所需的value,例如。 data.foo。如果不知道更多关于 data 的价值是什么,我们真的无能为力
  • 我能提供什么?如何获得数据的价值?不是null吗,因为我一开始就设置为null?
  • 添加它之前返回语句....
  • "一开始我将其设置为 null" - 这是 两个不同的变量 - render:function(data) 中的一个被传递数据表,data:null(甚至不是变量)仅用于将数据传递给数据表

标签: javascript jquery model-view-controller datatables


【解决方案1】:

如果数据为空,这将用“空”字符串填充输入,否则将显示 data.toString()。如果您更愿意使用 JSON 表示的数据(或其他内容),只需相应地解析它,例如JSON.parse:

data: null,
name: "MillerLite",
render: function (data, type, row) {
    if (type === 'display') {
        return '<input name="MillerLite" value="' + (data ? data.toString() : 'null') + '" />';
    }
    return data;
}

【讨论】:

  • 哈哈 - 否定。这给了我输入中值的文字字符串
  • 这不是你想要的吗?如果你有一些数据,你会显示它的字符串表示,如果没有,你什么都不显示......
  • 不,我的意思是输入框显示"${data ? data.toString() : ""}"
  • 哦,对不起。模板字符串是 ES6,看起来你没有使用转译器。我会更新答案...
  • 我正在使用 .net core 和 mvc
【解决方案2】:

您可以使用ternary operator 并将新变量设置为您想要的任何值、空字符串、“null”等:

data: null,
name: "MillerLite",
render: function (data, type, row) {

    //let myData = (data === null) ? "" : data;
    // if data is an object:
    let myData = (Object.entries(data).length === 0) ? "" : data;

    if (type === 'display') {
        return '<input name="MillerLite" value="' + myData + '" />';
    }
    return data;
}

【讨论】:

  • 我得到一个开发控制台错误“Uncaught ReferenceError: isNull is not defined
  • 抱歉把我的语法弄混了
  • 问题是因为data是一个对象并且被强制转换为一个字符串,而不是它为空
  • @Michael- 仍然得到 [object Object]
  • 好的,然后用Object.entries(obj).length === 0检查一个空对象
猜你喜欢
  • 1970-01-01
  • 2021-04-05
  • 2021-07-15
  • 2021-05-14
  • 2014-07-28
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多