使用jQuery更改表格单元格的背景颜色

时间:2022-11-21 15:50:54

I have got a table with 6 rows and x columns. I need to change background color of cells to color which contains in array. Index of color matches how many rows should be painted. I have next array of colors:

我有一个包含6行和x列的表。我需要将单元格的背景颜色更改为包含在数组中的颜色。颜色索引匹配应绘制的行数。我有下一组颜色:

var arr = ["lightgreen", "orange", "red"];

And my jQuery script:

我的jQuery脚本:

$.each(arr, function(index, val) {
$("tr:eq(" + (index) + ")").css("background-color", val);
});

This piece of code only paint first three rows in different colors. I need output table like this:

这段代码只绘制不同颜色的前三行。我需要像这样的输出表:

lightgreen lightgreen lightgreen lightgreen
orange orange orange orange
orange orange orange orange
red red red red
red red red red
red red red red

My jsfiddle: http://jsfiddle.net/kvdokq13/

我的jsfiddle:http://jsfiddle.net/kvdokq13/

4 个解决方案

#1


2  

You want to process N rows at each time, while using $("tr:eq(" + (index) + ")") only selects the unique Nth row!

你想每次处理N行,而使用$(“tr:eq(”+(index)+“)”)只选择唯一的第N行!

You can achieve it like this:

你可以像这样实现它:

var arr = ["lightgreen", "orange", "red"];
var $rows = $('tr');
var nextRow = 0;
$.each(arr, function(index, val) {
    for (var i = 0; i < index + 1; i++) {
    $rows.eq(nextRow++).css("background-color", val);
  }
});

http://jsfiddle.net/kvdokq13/6/

For a more general use, note that this should be enhanced to properly take care of differences between the array length and the number of rows: currently it assumes that there are exactly (1 + 2 + ... + N) rows!

为了更广泛的使用,请注意这应该得到增强,以正确处理数组长度和行数之间的差异:目前它假设有完全(1 + 2 + ... + N)行!

#2


0  

modified Azim's asnwer...

修改了Azim的asnwer ......

var arr = ["lightgreen", "orange", "red"];
var tr = $('table tr');

for (var i=0; i<tr.length; i++){
  $(tr[i]).css("background-color", arr[i]);
   if (i>2){
        $(tr[i]).css("background-color", arr[2]);
  }    
}

http://jsfiddle.net/kvdokq13/5/

this could be more efficient using only css but I am guessing that JQuery is a must?

这可能只使用css更有效但我猜JQuery是必须的?

#3


0  

You should hold number how much rows you need to skip:

您应该保留数字需要跳过多少行:

var arr = ["lightgreen", "orange", "red"];
var skip = 0;
$.each(arr, function(index, val) {
    var _repeat = index+1; // js arrays are zero indexed
    for (var i = 0; i < _repeat; i++) 
        $("tr:eq(" + (i+skip) + ")").css("background-color", val);
  skip = skip + _repeat;
});

updated fiddle

#4


0  

While you've already accepted an answer to this question, I thought I'd throw in an alternative using plain JavaScript, rather than a library, just in case that might be useful.

虽然你已经接受了这个问题的答案,但我认为我会使用普通的JavaScript而不是库来提供替代方案,以防万一可能有用。

Note that I've used some ECMAScript 6 features, the 'fat arrow' syntax and Array.from() (see the references below), though I'll post an alternative (below the 'primary' part of my answer to show an alternative implementation if you'd rather not use ES6 just yet).

请注意,我已经使用了一些ECMAScript 6功能,'胖箭头'语法和Array.from()(参见下面的参考资料),虽然我会发布一个替代方案(在我的答案的'主要'部分下面显示一个如果您还不想使用ES6,那么替代实现。

That said, my own solution is the follwing:

也就是说,我自己的解决方案是:

// the colors Array:
var colors = ["lightgreen", "orange", "red"],
// a reference to the <table> element that is
// to be coloured:
  table = document.querySelector('table');

// declaring the relevant function to handle the 
// colouring:
function colorNRows(arr, table) {

  // caching the rows of the table:
  var rows = table.rows,

  // using Array.from() to convert the HTMLCollection
  // into an Array:
    clone = Array.from(rows),

  // iterating over the array of colours, using
  // Array.prototype.map(),
  // row:   the array-element of the array over which
  //        we're iterating,
  // index: the index of the current array-element
  //        in that array,
  // array: (unused here), the array over which we're
  //        iterating.
    segments = arr.map(function(row, index, array) {

      // removing 'index+1' elements of the array from
      // the clone Array, starting at index 0 and
      // returning the removed row(s) to form a new
      // Array:
      return clone.splice(0, index + 1);

    // iterating over the newly-formed Array,
    // using Array.prototype.forEach();
    // the automagically-passed array-elements
    // are, as above, the array-element (of the new
    // array) and the index of the current
    // array-element (in that array):
    }).forEach(function(rowSegments, index) {

      // here we iterate over the array(s) held
      // in each array-element, again using the
      // automagic variables are the same as above
      // relative to the current array.

      // we're using the 'fat arrow' syntax to pass
      // the array-element (toColor) into the
      // the process on the right hand side, thereby
      // styling the backgroundColor of each array-element
      // (a <tr>) according to the color held in the 'arr'
      // array, at the index held in the outer forEach():
      rowSegments.forEach(toColor => toColor.style.backgroundColor = arr[index]);
    });
}

// calling the function:
colorNRows(colors, table);

var colors = ["lightgreen", "orange", "red"],
  table = document.querySelector('table');

function colorNRows(arr, table) {
  var rows = table.rows,
    clone = Array.from(rows),
    segments = arr.map(function(row, index, array) {
      return clone.splice(0, index + 1);
    }).forEach(function(rowSegments, index) {
      rowSegments.forEach(toColor => toColor.style.backgroundColor = arr[index]);
    });
}

colorNRows(colors, table);
<table border="4" cellpadding="4" cellspacing="4">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
  </tr>
  <tr>
    <td>11</td>
    <td>12</td>
    <td>13</td>
    <td>14</td>
    <td>15</td>
    <td>16</td>
    <td>17</td>
    <td>18</td>
    <td>19</td>
    <td>20</td>
  </tr>
  <tr>
    <td>21</td>
    <td>22</td>
    <td>23</td>
    <td>24</td>
    <td>25</td>
    <td>26</td>
    <td>27</td>
    <td>28</td>
    <td>29</td>
    <td>30</td>
  </tr>
  <tr>
    <td>31</td>
    <td>32</td>
    <td>33</td>
    <td>34</td>
    <td>35</td>
    <td>36</td>
    <td>37</td>
    <td>38</td>
    <td>39</td>
    <td>40</td>
  </tr>
  <tr>
    <td>41</td>
    <td>42</td>
    <td>43</td>
    <td>44</td>
    <td>45</td>
    <td>46</td>
    <td>47</td>
    <td>48</td>
    <td>49</td>
    <td>50</td>
  </tr>
  <tr>
    <td>51</td>
    <td>52</td>
    <td>53</td>
    <td>54</td>
    <td>55</td>
    <td>56</td>
    <td>57</td>
    <td>58</td>
    <td>59</td>
    <td>60</td>
  </tr>
</table>

JS Fiddle demo.

JS小提琴演示。

Removing the ES6 features, to be compatible with the majority of modern browsers, leaves us with the following (everything but the commented code is precisely the same):

删除ES6功能,与大多数现代浏览器兼容,给我们留下了以下内容(除了注释代码之外的所有功能都完全相同):

function colorNRows(arr, table) {
  var rows = table.rows,

  // cloning the rows HTMLCollection, using
  // Array.prototype.slice() in conjunction with
  // Function.prototype.call(), to allow us to use
  // slice() on the Array-like collection:
    clone = Array.prototype.slice.call(rows, 0),

    segments = arr.map(function(row, index, array) {
      return clone.splice(0, index + 1);
    }).forEach(function(rowSegments, index) {

      // here, rather than a fat arrow function,
      // we explicitly use an inner forEach() loop
      // performing the same action, but slightly
      // more verbose:
      rowSegments.forEach(function(toColor) {
        toColor.style.backgroundColor = arr[index];
      })
    });
}

var colors = ["lightgreen", "orange", "red"],
  table = document.querySelector('table');

function colorNRows(arr, table) {
  var rows = table.rows,
    clone = Array.prototype.slice.call(rows, 0),
    segments = arr.map(function(row, index, array) {
      return clone.splice(0, index + 1);
    }).forEach(function(rowSegments, index) {
      rowSegments.forEach(function(toColor) {
        toColor.style.backgroundColor = arr[index];
      })
    });
}

colorNRows(colors, table);
<table border="4" cellpadding="4" cellspacing="4">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
  </tr>
  <tr>
    <td>11</td>
    <td>12</td>
    <td>13</td>
    <td>14</td>
    <td>15</td>
    <td>16</td>
    <td>17</td>
    <td>18</td>
    <td>19</td>
    <td>20</td>
  </tr>
  <tr>
    <td>21</td>
    <td>22</td>
    <td>23</td>
    <td>24</td>
    <td>25</td>
    <td>26</td>
    <td>27</td>
    <td>28</td>
    <td>29</td>
    <td>30</td>
  </tr>
  <tr>
    <td>31</td>
    <td>32</td>
    <td>33</td>
    <td>34</td>
    <td>35</td>
    <td>36</td>
    <td>37</td>
    <td>38</td>
    <td>39</td>
    <td>40</td>
  </tr>
  <tr>
    <td>41</td>
    <td>42</td>
    <td>43</td>
    <td>44</td>
    <td>45</td>
    <td>46</td>
    <td>47</td>
    <td>48</td>
    <td>49</td>
    <td>50</td>
  </tr>
  <tr>
    <td>51</td>
    <td>52</td>
    <td>53</td>
    <td>54</td>
    <td>55</td>
    <td>56</td>
    <td>57</td>
    <td>58</td>
    <td>59</td>
    <td>60</td>
  </tr>
</table>

JS Fiddle demo.

JS小提琴演示。

References:

#1


2  

You want to process N rows at each time, while using $("tr:eq(" + (index) + ")") only selects the unique Nth row!

你想每次处理N行,而使用$(“tr:eq(”+(index)+“)”)只选择唯一的第N行!

You can achieve it like this:

你可以像这样实现它:

var arr = ["lightgreen", "orange", "red"];
var $rows = $('tr');
var nextRow = 0;
$.each(arr, function(index, val) {
    for (var i = 0; i < index + 1; i++) {
    $rows.eq(nextRow++).css("background-color", val);
  }
});

http://jsfiddle.net/kvdokq13/6/

For a more general use, note that this should be enhanced to properly take care of differences between the array length and the number of rows: currently it assumes that there are exactly (1 + 2 + ... + N) rows!

为了更广泛的使用,请注意这应该得到增强,以正确处理数组长度和行数之间的差异:目前它假设有完全(1 + 2 + ... + N)行!

#2


0  

modified Azim's asnwer...

修改了Azim的asnwer ......

var arr = ["lightgreen", "orange", "red"];
var tr = $('table tr');

for (var i=0; i<tr.length; i++){
  $(tr[i]).css("background-color", arr[i]);
   if (i>2){
        $(tr[i]).css("background-color", arr[2]);
  }    
}

http://jsfiddle.net/kvdokq13/5/

this could be more efficient using only css but I am guessing that JQuery is a must?

这可能只使用css更有效但我猜JQuery是必须的?

#3


0  

You should hold number how much rows you need to skip:

您应该保留数字需要跳过多少行:

var arr = ["lightgreen", "orange", "red"];
var skip = 0;
$.each(arr, function(index, val) {
    var _repeat = index+1; // js arrays are zero indexed
    for (var i = 0; i < _repeat; i++) 
        $("tr:eq(" + (i+skip) + ")").css("background-color", val);
  skip = skip + _repeat;
});

updated fiddle

#4


0  

While you've already accepted an answer to this question, I thought I'd throw in an alternative using plain JavaScript, rather than a library, just in case that might be useful.

虽然你已经接受了这个问题的答案,但我认为我会使用普通的JavaScript而不是库来提供替代方案,以防万一可能有用。

Note that I've used some ECMAScript 6 features, the 'fat arrow' syntax and Array.from() (see the references below), though I'll post an alternative (below the 'primary' part of my answer to show an alternative implementation if you'd rather not use ES6 just yet).

请注意,我已经使用了一些ECMAScript 6功能,'胖箭头'语法和Array.from()(参见下面的参考资料),虽然我会发布一个替代方案(在我的答案的'主要'部分下面显示一个如果您还不想使用ES6,那么替代实现。

That said, my own solution is the follwing:

也就是说,我自己的解决方案是:

// the colors Array:
var colors = ["lightgreen", "orange", "red"],
// a reference to the <table> element that is
// to be coloured:
  table = document.querySelector('table');

// declaring the relevant function to handle the 
// colouring:
function colorNRows(arr, table) {

  // caching the rows of the table:
  var rows = table.rows,

  // using Array.from() to convert the HTMLCollection
  // into an Array:
    clone = Array.from(rows),

  // iterating over the array of colours, using
  // Array.prototype.map(),
  // row:   the array-element of the array over which
  //        we're iterating,
  // index: the index of the current array-element
  //        in that array,
  // array: (unused here), the array over which we're
  //        iterating.
    segments = arr.map(function(row, index, array) {

      // removing 'index+1' elements of the array from
      // the clone Array, starting at index 0 and
      // returning the removed row(s) to form a new
      // Array:
      return clone.splice(0, index + 1);

    // iterating over the newly-formed Array,
    // using Array.prototype.forEach();
    // the automagically-passed array-elements
    // are, as above, the array-element (of the new
    // array) and the index of the current
    // array-element (in that array):
    }).forEach(function(rowSegments, index) {

      // here we iterate over the array(s) held
      // in each array-element, again using the
      // automagic variables are the same as above
      // relative to the current array.

      // we're using the 'fat arrow' syntax to pass
      // the array-element (toColor) into the
      // the process on the right hand side, thereby
      // styling the backgroundColor of each array-element
      // (a <tr>) according to the color held in the 'arr'
      // array, at the index held in the outer forEach():
      rowSegments.forEach(toColor => toColor.style.backgroundColor = arr[index]);
    });
}

// calling the function:
colorNRows(colors, table);

var colors = ["lightgreen", "orange", "red"],
  table = document.querySelector('table');

function colorNRows(arr, table) {
  var rows = table.rows,
    clone = Array.from(rows),
    segments = arr.map(function(row, index, array) {
      return clone.splice(0, index + 1);
    }).forEach(function(rowSegments, index) {
      rowSegments.forEach(toColor => toColor.style.backgroundColor = arr[index]);
    });
}

colorNRows(colors, table);
<table border="4" cellpadding="4" cellspacing="4">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
  </tr>
  <tr>
    <td>11</td>
    <td>12</td>
    <td>13</td>
    <td>14</td>
    <td>15</td>
    <td>16</td>
    <td>17</td>
    <td>18</td>
    <td>19</td>
    <td>20</td>
  </tr>
  <tr>
    <td>21</td>
    <td>22</td>
    <td>23</td>
    <td>24</td>
    <td>25</td>
    <td>26</td>
    <td>27</td>
    <td>28</td>
    <td>29</td>
    <td>30</td>
  </tr>
  <tr>
    <td>31</td>
    <td>32</td>
    <td>33</td>
    <td>34</td>
    <td>35</td>
    <td>36</td>
    <td>37</td>
    <td>38</td>
    <td>39</td>
    <td>40</td>
  </tr>
  <tr>
    <td>41</td>
    <td>42</td>
    <td>43</td>
    <td>44</td>
    <td>45</td>
    <td>46</td>
    <td>47</td>
    <td>48</td>
    <td>49</td>
    <td>50</td>
  </tr>
  <tr>
    <td>51</td>
    <td>52</td>
    <td>53</td>
    <td>54</td>
    <td>55</td>
    <td>56</td>
    <td>57</td>
    <td>58</td>
    <td>59</td>
    <td>60</td>
  </tr>
</table>

JS Fiddle demo.

JS小提琴演示。

Removing the ES6 features, to be compatible with the majority of modern browsers, leaves us with the following (everything but the commented code is precisely the same):

删除ES6功能,与大多数现代浏览器兼容,给我们留下了以下内容(除了注释代码之外的所有功能都完全相同):

function colorNRows(arr, table) {
  var rows = table.rows,

  // cloning the rows HTMLCollection, using
  // Array.prototype.slice() in conjunction with
  // Function.prototype.call(), to allow us to use
  // slice() on the Array-like collection:
    clone = Array.prototype.slice.call(rows, 0),

    segments = arr.map(function(row, index, array) {
      return clone.splice(0, index + 1);
    }).forEach(function(rowSegments, index) {

      // here, rather than a fat arrow function,
      // we explicitly use an inner forEach() loop
      // performing the same action, but slightly
      // more verbose:
      rowSegments.forEach(function(toColor) {
        toColor.style.backgroundColor = arr[index];
      })
    });
}

var colors = ["lightgreen", "orange", "red"],
  table = document.querySelector('table');

function colorNRows(arr, table) {
  var rows = table.rows,
    clone = Array.prototype.slice.call(rows, 0),
    segments = arr.map(function(row, index, array) {
      return clone.splice(0, index + 1);
    }).forEach(function(rowSegments, index) {
      rowSegments.forEach(function(toColor) {
        toColor.style.backgroundColor = arr[index];
      })
    });
}

colorNRows(colors, table);
<table border="4" cellpadding="4" cellspacing="4">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
  </tr>
  <tr>
    <td>11</td>
    <td>12</td>
    <td>13</td>
    <td>14</td>
    <td>15</td>
    <td>16</td>
    <td>17</td>
    <td>18</td>
    <td>19</td>
    <td>20</td>
  </tr>
  <tr>
    <td>21</td>
    <td>22</td>
    <td>23</td>
    <td>24</td>
    <td>25</td>
    <td>26</td>
    <td>27</td>
    <td>28</td>
    <td>29</td>
    <td>30</td>
  </tr>
  <tr>
    <td>31</td>
    <td>32</td>
    <td>33</td>
    <td>34</td>
    <td>35</td>
    <td>36</td>
    <td>37</td>
    <td>38</td>
    <td>39</td>
    <td>40</td>
  </tr>
  <tr>
    <td>41</td>
    <td>42</td>
    <td>43</td>
    <td>44</td>
    <td>45</td>
    <td>46</td>
    <td>47</td>
    <td>48</td>
    <td>49</td>
    <td>50</td>
  </tr>
  <tr>
    <td>51</td>
    <td>52</td>
    <td>53</td>
    <td>54</td>
    <td>55</td>
    <td>56</td>
    <td>57</td>
    <td>58</td>
    <td>59</td>
    <td>60</td>
  </tr>
</table>

JS Fiddle demo.

JS小提琴演示。

References: