你如何使用jQuery创建一个表?

时间:2015-05-14 19:10:27

标签: javascript jquery html-table

我要做的是仅使用jQuery创建一个表(7列和5行)。这是一周的日子(例如星期一,星期二等)

这是我在jQuery中尝试创建的HTML版本:

<table id="table">
  <tr>
    <th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th>
  </tr>
  <tr>
    <td>1</td><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td>
  </tr>
  <tr>
    <td>2</td><td>2</td><td>2</td><td>2</td><td>2</td><td>2</td><td>2</td>
  </tr>
  <tr>
    <td>3</td><td>3</td><td>3</td><td>3</td><td>3</td><td>3</td><td>3</td>
  </tr>
  <tr>
    <td>4</td><td>4</td><td>4</td><td>4</td><td>4</td><td>4</td><td>4</td>
  </tr>

我还需要为背景颜色设置所有颜色的样式。然后其余的行是交替的颜色。请帮我解决这个问题。

这就是我所拥有的:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
      for(var i=0; i < 5; i++) {



        for(var j=0; j < 7; j++) {
          $("#container").append( "Sunday" + "Monday" + "Tuesday" + "Wednesday" + "Thursday" + "Friday" + "Saturday" + i );
          if (i == 0) {

            $("th").css("background-color", "#ccc");
          } else if {
            $(this).css("background-color", "red");
          }
        }
      }
      $("#container").append('</table>');
    });
</script>

2 个答案:

答案 0 :(得分:0)

这是单程......

&#13;
&#13;
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    rowCount = 4;

$(document).ready(function() {
    var table = $('<table/>'),
        head = $('<thead/>'),
        body = $('<tbody/>'),
        headrow = $('<tr/>');

    $.each(days, function(index, day) {
        headrow.append('<th>' + day + '</th>');
    });
    head.append(headrow);

    for (var i = 0; i < rowCount; i++) {
        var bRow = $('<tr/>');
        for (var j = 0; j < days.length; j++) {
            bRow.append('<td>' + (i + 1) + '</td>');
        }
        body.append(bRow);
    }
    table.append(head).append(body).appendTo('body');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这里你可以简化:

Set