bootstraptable中使用row传值问题

2023-09-27  本文已影响0人  阿乐_822e

bootstraptable中,常会碰到选择某行数据做特定操作。通常是选择id来传递参数。如:

$(function() {
  $('#table').bootstrapTable({
    data: [
      {id: 1, name: 'John', age: 25},
      {id: 2, name: 'Jane', age: 30},
      {id: 3, name: 'Tom', age: 28}
    ],
    columns: [{
      field: 'id',
      title: 'ID'
    }, {
      field: 'name',
      title: 'Name'
    }, {
      field: 'age',
      title: 'Age'
    }, {
      title: 'Actions',
      formatter: function(value, row) {
        return '<button onclick="doSomething(' + row.id + ')">Click</button>';
      }
    }]
  });
});

function doSomething(rowId) {
  // 在这里可以根据传入的 rowId 参数做你想要的操作
  console.log('Clicked on row with ID:', rowId);
  // 例如:根据 rowId 发起 API 请求,显示模态框等等
}

但有时,我们或许要多传一些参数过去,这时选择传递row就比较方便了,如下:

$(function() {
  $('#table').bootstrapTable({
    data: [
      {id: 1, name: 'John', age: 25},
      {id: 2, name: 'Jane', age: 30},
      {id: 3, name: 'Tom', age: 28}
    ],
    columns: [{
      field: 'id',
      title: 'ID'
    }, {
      field: 'name',
      title: 'Name'
    }, {
      field: 'age',
      title: 'Age'
    }, {
      title: 'Actions',
      formatter: function(value, row) {
        return '<button onclick="doSomething(' + JSON.stringify(row) + ')">Click</button>';
      }
    }]
  });
});

function doSomething(row) {
  // 在这里可以根据传入的 row 参数做你想要的操作
  console.log('Clicked on row:', row);
  console.log(' rowId:', row.id);
  // 例如:根据 row 的属性进行逻辑判断、调用其他函数等等
}

在这个新的示例中,我们将整个 row 对象通过 JSON.stringify() 方法转换为字符串,并作为参数传递给 doSomething 函数的调用,以便在按钮点击时将整个 row 对象传递给指定的函数。

当用户点击按钮时,doSomething 函数将被调用,并且完整的 row 对象将作为参数传递给该函数。

PS: JSON.stringify()的作用是将 JavaScript 对象转换为 JSON 字符串,而JSON.parse()可以将JSON字符串转为一个对象。两者功能刚好相反。

上面传递参数时,一定要做一下序列化,而不能直接传Object对象: onclick="doSomething(' + row + ')"

上一篇 下一篇

猜你喜欢

热点阅读