简体   繁体   English

在数据表中添加新行时如何向元素(标签)添加数据属性?

[英]How to add data attributes to elements (<td> tags) when adding new row in datatable?

I am adding new rows using JavaScript and inside a JavaScript function and I would like to add attributes and class names to the rows when they are created: I am adding new rows using JavaScript and inside a JavaScript function and I would like to add attributes and class names to the rows when they are created:

var rowNode = myTable.row.add([results.location_id, location_name.value, location_streetname.value , add_loc_hotline_phone ]).draw().node();

const $rowindex_ = $(rowNode).closest("tr");

const loc_city = $rowindex_.find('.location_address').attr('data-loc_city', location_city.value);
const loc_streetname = $rowindex_.find('.location_address').attr('data-loc_streetname', location_streetname.value);

Above you can see how I would update ALREADY existing attributes but HOW DO I CREATE THEM FIRST?在上面你可以看到我将如何更新已经存在的属性,但我如何首先创建它们?

UPDATE: I first need to create classNames for each of the rows because later I need to find tags by class names.更新:我首先需要为每一行创建类名,因为稍后我需要按 class 名称查找标签。 So how should I give them class names when the row is created?那么在创建行时我应该如何给他们 class 名称?

To add hidden data information to a row, you can use the data() function:要将隐藏的数据信息添加到一行,可以使用data() function:

var rowNode = myTable.row
  .add([results.location_id, location_name.value, 
        location_streetname.value, add_loc_hotline_phone])
  .data({city: location_city.value, streetname: location_streetname.value})
  .draw().node();

To add a class you can use the createdCell callback:要添加 class 您可以使用createdCell回调:

$('#container').dataTable( {
  // ...
  "columnDefs": [ {
    "targets": 0, // First column
    "createdCell": function (td, cellData, rowData, row, col) {
      td.classList.add(`column-id`);
    }
  } ]
} );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM