简体   繁体   中英

Dynamically created table with variable number of rows

I need to make table with number of rows equals to number of days in current month, can anyone help me with that? I need to create that dynamically using jquery or javascript.

You could do something like this:

function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}


var $table = $('<table>');
var $tbody = $('<tbody>');

var days=  daysInMonth(new Date().getMonth(), new Date().getYear());

$table.append($tbody);
for (i = 1; i<= days; i++){
    var $tr = $('<tr>');
    var $td = $('<td>');
    $td.text(i);
    $tr.append($td);
    $tbody.append($tr);
};
$('body').append($table);

fiddle here: http://jsfiddle.net/nicolapeluchetti/WG88Y/

This creates a table with a row for each day of the month. i included a td with the current day.

As long as we don't know with wich technology you want to do this. (pure javascript, jquery, asp.net webforms, asp.net mvc or other) the only thing i can say is.

You can loop over DateTime.DaysInMonth(DateTime.Now.Date.Year, DateTime.Now.Date.Month); wich contains the number of days in the current Month.

hope this helps

This is the jQuery part of @dknaack 's answer:

var genTable = function () {
  var $table = jQuery("<table />");
  // days is equeal to @dhnaack 's answer
  var days = DateTime.DaysInMonth(DateTime.Now.Date.Year, DateTime.Now.Date.Month);
  jQuery(days).each(function(i,e) {
    var $tr = jQuery("<tr />");
    var $tr = jQuery("<td />")
    $table.append($tr.append($td));
  });
  return $table;
}

Then you could use it like so:

jQuery("body").append(genTable());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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