简体   繁体   English

在 JavaScript 中创建表时如何创建表 header 的设置属性

[英]How to create set attribute to a table header when creating the table in JavaScriipt

I am trying to set a class attribute to a table head for proper styling in JavaScript. I have succeeded in creating the Table Headers but could not set the class attributes so that the styling in the CSS file can be applied.我正在尝试将class属性设置为table head ,以便在 JavaScript 中设置适当的样式。我已成功创建表头,但无法设置 class 属性,以便可以应用CSS文件中的样式。

The JavaScript JavaScript

// Create Classes for the table head styling
let tableSN = document.createAttribute("class");
let tableModel = document.createAttribute("class");
let tableDesc = document.createAttribute("class");
let tableQty = document.createAttribute("class");
let tableUnit = document.createAttribute("class");
let tableTotal = document.createAttribute("class");

// Set names to the Classes
tableSN.value= "sn";
tableModel.value = "model";
tableDesc.value = "desc";
tableQty.value = "qty";
tableUnit.value = "unit";
tableTotal.value = "total";


// Create Table Headings  and Classes List
let headers = ['SN', 'MODEL', 'DESCRIPTION', 'PRICE', 'QTY', 'AMOUNT'];
let myClasses = [tableSN, tableModel, tableDesc, tableQty, tableUnit, tableTotal];

// Select the DIV table container
let tableContainer = document.querySelector('#table');

// Create the table elements
let table = document.createElement('table');
let headerContainer = document.createElement('thead');
let headerRow = document.createElement('tr');

//Create the table headers
headers.forEach(headerText => {
   let header = document.createElement('th');
          
   // This is my problem. I want to attach each `class` to each table `head` created.
   for(let i=0; i < myClasses.length; i++ ) {
          header.setAttribute = myClasses[i];
   }

   let textNode = document.createTextNode(headerText);
          
   header.appendChild(textNode);
   headerRow.appendChild(header);
});

headerContainer.appendChild(headerRow);
table.appendChild(headerContainer);

Table works well, except the Classes are not attaching.表运行良好,除了类没有附加。

You think too complicated.你想的太复杂了。 Just add the class name to your element using classlist.add只需使用 classlist.add 将 class 名称添加到您的元素中

const myClasses = ["className1", "className2"];

headers.forEach(headerText => {
   let header = document.createElement('th');
   myClasses.forEach(className => header.classList.add(className));
   let textNode = document.createTextNode(headerText);          
   header.appendChild(textNode);
   headerRow.appendChild(header);
});

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

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