Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Add multiple new attributes by checking the existing ones

I am working on a reporting application that pulls info from different servers and displays them in a specific format. I am also making this completely responsive so the tables that I get look something like this:

<table>
  <tr>
    <td width="30%">Date</td>
    <td width="40%">Description</td>
    <td width="17%">Result</td>
    <td width="15%">Range</td>
    <td width="8%">Comments</td>
  </tr>
</table>

I want to know how I could add data-label to each depending on what width they have.

like

<td width="30%" data-label="Date">Date</td>

I don't actually need the date field so I have hidden that entire field with CSS its just the description, result, range and comments.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pulling a list of all td elements in the document, and applying the appropriate labels when the widths-in-question are seen:

var tds = document.getElementsByTagName('td');

for ( var i = 0; i < tds.length; ++i )
  {
    var td = tds[i];
    var label = null;
    
    switch (td.getAttribute('width'))
    {
      case '30%':
        label = 'Date';
        break;
      case '40%':
        label = 'Description';
        break;
      case '17%':
        label = 'Result';
        break;
      case '15%':
        label = 'Range';
        break;
      case '8%':
        label = 'Comments';
        break;
    }
    
    if (label)
      {
        td.setAttribute('data-label', label);
      }
  }
td[data-label=Date] {
  color: red;
}

td[data-label=Description] {
  color: green;
}

td[data-label=Result] {
  color: purple;
}

td[data-label=Range] {
  color: blue;
}

td[data-label=Comments] {
  font-style: italic;
}
<table>
  <tr>
    <td width="30%">Date</td>
    <td width="40%">Description</td>
    <td width="17%">Result</td>
    <td width="15%">Range</td>
    <td width="8%">Comments</td>
  </tr>
  <tr>
    <td width="30%">Blah</td>
    <td width="40%">Blah</td>
    <td width="17%">Blah</td>
    <td width="15%">Blah</td>
    <td width="8%">Blah</td>
  </tr>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...