需要将事件添加到日历

时间:2017-03-20 01:20:11

标签: javascript html arrays events calendar

我目前拥有创建月历的代码:

 var i = 1;

 do{

     var writeDays = new Date(year, month, i).getDay();
     //if it's Sunday, start a new row
     if(writeDays == 0)
     {
         html += '<tr>';
     }
     //if it's not Sunday but the first day of the month, write the last days from the previous month
     else if(i == 1)
     {
         html += '<tr>';
         var count = lastDayofPreviousMonth - firstDayofMonth + 1;
         for(var j = 0; j < firstDayofMonth; j++)
         {
             html += '<td class = "not-current">' + count + '</td>';
             count++;

         }
     }

     html += '<td class = "hover">' + i  + '</td>';


     //if it's Saturday, ends the row
     if(writeDays == 6)
     {
     html += '</tr>';
     }
     //if it isn't Saturday, but last day of the current month, write the next few days from the next month
     else if(i == lastDayofMonth)
     {
     var count = 1;
     for(writeDays; writeDays < 6; writeDays++)
     {
     html += '<td class = "not-current">' + count + '</td>';
     count++;
     }
     }
     i++;
 }
 while(i <= lastDayofMonth);

我希望能够点击数组中的一天(单元格)并在当天添加一个事件。我不太清楚如何实现这一点。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以将eventListener添加到表元素中。 例如。我有一个像这样的桌子,我认为这与你的dom结构类似:

<table id='tb'>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
 </table>

我希望每个td元素都可以响应点击事件,所以我可以这样做:

var table=document.getElementById('tb');
table.addEventListener('click',function(e){
  console.log(e);
});

在参数e中,您可以获得大量信息。只需尝试一下。