如何正确使用 JavaScript DOM 方法替换字符串连接

问题描述 投票:0回答:1

这是我的活动日历学校作业的第二部分。

老师让我们换掉一些没有使用最佳实践的代码。 任务通过使用文档对象模型方法替换字符串连接和输出来改进代码。

这是老师提供的代码和我从作业 1 中插入的代码的混合体。

不是我需要帮助的代码。这只是正在被交换的东西。 我需要帮助的代码位于下面的 JavaScript 标题下。

// declare an object Calendar
function Calendar(elem) {

    // HTML element in which to display the calendar
    this.elem = elem;
    
    // array containing list of names of the days of the week 
    this.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    
    /** Returns the month name of the year for a given month index.
     * @param monthIndex {number} zero-based index of the month of the year (0 = January, 11 = December)
     * @returns {string} the name of the given month
     */
    this.getMonth = function(monthIndex) {  
  
      // replace this with your solution from Assignment 1!
      switch(monthIndex) {
        case 0:
          return "January";
        case 1:
          return "February";
        case 2:
          return "March";
        case 3:
          return "April";
        case 4:
          return "May";
        case 5:
          return "June";
        case 6:
          return "July";
        case 7:
          return "August";
        case 8:
          return "September";
        case 9:
          return "October";
        case 10:
          return "November";
        case 11:
          return "December";
    }
    if (!isNaN(monthIndex))
      return("Unknown");      
      }
      
    
    /** Returns the number of days in the month for a given zero-based month index and year.
     * @param monthIndex {number} zero-based index of the month of the year (0 = January, 11 = December)
     * @param year {number} a 4-digit year
     * @returns {number} the number of days in the given month and year
     */
    this.getDaysInMonth = function(monthIndex, year) {
      
      // replace this with your solution from Assignment 1!
      if (monthIndex <= -1) {
        return "-1";
    }
      if (typeof year == 'string') {
        return "-1";
    }
      if (monthIndex === 0) {
        return "28";
    }
       if (monthIndex >= 12) {
         return "-1";
    }
      if (year % 400 === 0) {
        return "29";
    }
      if (typeof year == 'string') {
        return "-1";
    }
      if (monthIndex == 1) {
        return "28";
    }
      if (monthIndex == 2) {
        return "31";
    }
      if (monthIndex == 3) {
        return "30";
    }
      if (monthIndex == 4) {
        return "31";
    }
      if (monthIndex == 5) {
        return "30";
    }
      if (monthIndex == 6) {
        return "31";
    }
      if (monthIndex == 7) {
        return "30";
    }
      if (monthIndex == 8) {
        return "30";
    }
      if (monthIndex == 9) {
        return "31";
    }
      if (monthIndex == 10) {
        return "30";
    }
      if (monthIndex == 11) {
        return "31";
    }
      if (monthIndex = typeof str) {
        return "-1";
    }
      if (year == typeof str) {
        return "-1";
    }
      if (monthIndex = 0, year = "twenty twenty-three") {
        return "-1";
    }
        
      }
     
    // method display generates calendar HTML
    // the displayDate parameter indicates the year and month to render (display) 
    this.display = function(displayDate = new Date()) {
      
      // clear the calendar element
      this.elem.innerHTML = "";
      
      // get the number of days in the month
      let daysInMonth = this.getDaysInMonth(displayDate.getMonth(), displayDate.getFullYear());
      
      // get array of days to display
      let days = [];
      for (let i = 1; i <= daysInMonth; i++) {
        days.push(new Date(displayDate.getFullYear(), displayDate.getMonth(),i));
      }
      
      let iHTML = '';
      
      // generate tabular calendar
      iHTML += '<table>';
      iHTML += '<thead>';
      
      // a row containing the previous month button, month name and year, and next month button 
      // the previous and next month buttons call the cal.display() method when clicked
      // with parameters of year displayed, but previous or next month
      // dates will "carry forward", increasing or decreasing the year automatically
      iHTML += '<tr>';
      iHTML += '<td>';
      iHTML += '<button \
                  value="Previous Month" \
                  onclick="cal.display(new Date(' + displayDate.getFullYear() + ',' + (displayDate.getMonth() - 1) + '));">';
      iHTML += '&lt;&lt;';
      iHTML += '</button>';
      iHTML += '</td>';
      iHTML += '<td colspan="5">';
      iHTML += '<h1>';
      iHTML += this.getMonth(displayDate.getMonth()) + " " + displayDate.getFullYear();
      iHTML += '</h1>';
      iHTML += '</td>';
      iHTML += '<td>';
      iHTML += '<button \
                  value="Next Month" \
                  onclick="cal.display(new Date(' + displayDate.getFullYear() + ',' + (displayDate.getMonth() + 1) + '));">';
      iHTML += '&gt;&gt;';
      iHTML += '</button>';
      iHTML += '</td>';
      iHTML += '</tr>';
    
      // row of weekday name headers
      // loop through the array, creating a table header cell for each element in the array 
      iHTML += "<tr>";
      for (const elem of this.dayNames) {
        iHTML += '<th>';
        iHTML += elem;
        iHTML += '</th>';
      }
      iHTML += '</tr>';
      
      // end the table head section, and start the table body section 
      iHTML += '</thead>';
      iHTML += '<tbody>';
      
  
      // calendar table body rows (days of the month)
      // start with blank cells until 1st of month
      iHTML += '<tr>';
      
      // loop from 0 until the first day of the month (Sunday, until the day of the week of the first day of the month)
      // create an empty table cell for each blank day 
      for (let i = 0; i < days[0].getDay(); i++) {
        iHTML += '<td></td>';
      }
      
      // for each day within the month, create a table cell containing the date 
      for (let i = 0; i < days.length; i++) {
        // if this day is a Sunday, end the previous week table row, and start a new row 
        if (days[i].getDay() == 0) {
          iHTML += '</tr>';
          iHTML += '<tr>';
        }
        
        // create a table cell with the CSS class "day", and the text value of the day of the month 
        iHTML += '<td class="day">';
        iHTML += days[i].getDate();
        iHTML += '</td>';
      }
      // last week of month empty cells to fill the week 
      // create an empty table cell for each blank day 
      for (let i = days.at(-1).getDay() + 1; i < 7; i++) {
        iHTML += '<td></td>';
      }
      iHTML += '</tr>';
      
      
      // end the table body section and calendar table 
      iHTML += '</tbody>';
      iHTML += '</table>';
      
      // output the calendar to the HTML element
      this.elem.innerHTML += iHTML;
    }
  }
  
  // declare a instance of Calendar
  const cal = new Calendar(document.getElementById("calendar"));
  
  // call the display() method
  cal.display();

我花了无数时间使用学校的材料、同学和在线资源,但没有成功。

目前,我的日历显示为黑色页面。

这是我用JS写的,HTML如下。

我的JavaScript

// declare an object Calendar
function Calendar(elem) {

  // HTML element in which to display the calendar
  this.elem = elem;
  
  // array containing list of names of the days of the week 
  this.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  
  /** Returns the month name of the year for a given month index.
   * @param monthIndex {number} zero-based index of the month of the year (0 = January, 11 = December)
   * @returns {string} the name of the given month
   */
  this.getMonth = function(monthIndex) {  
  // replace this with your solution from Assignment 1!
    switch(monthIndex) {
    case 0:
      return "January";
    case 1:
      return "February";
    case 2:
      return "March";
    case 3:
      return "April";
    case 4:
      return "May";
    case 5:
      return "June";
    case 6:
      return "July";
    case 7:
      return "August";
    case 8:
      return "September";
    case 9:
      return "October";
    case 10:
      return "November";
    case 11:
      return "December";
}
if (!isNaN(monthIndex))
  return("Unknown");      
  }
  
  /** Returns the number of days in the month for a given zero-based month index and year.
   * @param monthIndex {number} zero-based index of the month of the year (0 = January, 11 = December)
   * @param year {number} a 4-digit year
   * @returns {number} the number of days in the given month and year
   */
  this.getDaysInMonth = function(monthIndex, year) {
    
    // replace this with your solution from Assignment 1!
    if (monthIndex <= -1) {
    return "-1";
}
  if (typeof year == 'string') {
    return "-1";
}
  if (monthIndex === 0) {
    return "28";
}
   if (monthIndex >= 12) {
     return "-1";
}
  if (year % 400 === 0) {
    return "29";
}
  if (typeof year == 'string') {
    return "-1";
}
  if (monthIndex == 1) {
    return "28";
}
  if (monthIndex == 2) {
    return "31";
}
  if (monthIndex == 3) {
    return "30";
}
  if (monthIndex == 4) {
    return "31";
}
  if (monthIndex == 5) {
    return "30";
}
  if (monthIndex == 6) {
    return "31";
}
  if (monthIndex == 7) {
    return "30";
}
  if (monthIndex == 8) {
    return "30";
}
  if (monthIndex == 9) {
    return "31";
}
  if (monthIndex == 10) {
    return "30";
}
  if (monthIndex == 11) {
    return "31";
}
  if (monthIndex = typeof str) {
    return "-1";
}
  if (year == typeof str) {
    return "-1";
}
  if (monthIndex = 0, year = "twenty twenty-three") {
    return "-1";
}
    
  }

   
  // the displayDate parameter indicates the year and month to render (display) 
  this.display = function(displayDate = new Date()) {
    
    // clear the calendar element
    this.elem.innerHTML = "";
    
    // get the number of days in the month
    let daysInMonth = this.getDaysInMonth(displayDate.getMonth(), displayDate.getFullYear());
    
    // get array of days to display
    let days = [];
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(new Date(displayDate.getFullYear(), displayDate.getMonth(), i));
    }
    
    // Creating the table
    var table = document.createElement(table);
    document.body.appendChild(table);

    // Creating the table header within the table
    var thead = document.createElement(thead);
    document.body.appendChild(thead);

    // Creating the table header row
    var headerRow = document.createElement(tr);

    // Creating previous month button
    var prevMonthButton = document.createElement(button);
    prevMonthButton.value = "Previous Month";
    prevMonthButton.onclick = function() {
      cal.display(new Date(displayDate.getFullYear(), displayDate.getMonth() - 1));
    };
    prevMonthButton.textContent = '<<';

    var prevMonthCell = document.createElement(td);
    prevMonthCell.appendChild(prevMonthButton);
    headerRow.appendChild(prevMonthCell);

  
    // Creating Month and Year Header
    var monthYearCell = document.createElement(td);
    monthYearCell.colSpan = "5";
    var monthYearHeading = document.createElement(h1)
    monthYearHeading.textContent = this.getMonth(displayDate.getMonth()) + " " + displayDate.getFullYear();
    monthYearCell.appendChild(monthYearHeading);
    headerRow.appendChild(monthYearCell);

    // Creating next month button
    var nextMonthButton = document.createElement(button);
    nextMonthButton.value = "Next Month";
    nextMonthButton.onclick = function() {
      cal.display(new Date(displayDate.getFullYear(), displayDate.getMonth() + 1));
    };
    nextMonthButton.textContent = '>>';

    var nextMonthCell = document.createElement(td);
    nextMonthCell.appendChild(nextMonthButton);
    headerRow.appendChild(nextMonthCell);

    thead.appendChild(headerRow);

    // Create calendar table body element
    var tbody = document.createElement(tbody);
    table.appendChild(tbody);

    // Create row of weekday name headers
    var dayNamesRow = document.createElement(tr);
    this.dayNames.forEach(function(dayName) {
      let th = document.createElement(th);
      th.textContent = dayName;
      dayNamesRow.appendChild(th);
    });
    thead.appendChild(dayNamesRow);

    // Create calendar table body rows (days of the month)
    var currentRow;
    days.forEach(function(day, index) {
      if (index % 7 == 0) {
        currentRow = document.createElement(tr);
        tbody.appendChild(currentRow);
      }
      var dayCell = document.createElement(td);
      dayCell.classList.add(day);
      dayCell.textContent = day.getDate();
      currentRow.appendChild(dayCell);
    });

    // Create last week of month empty cells to fill the week
    if (currentRow) {
      var remainingCells = 7 - currentRow.children.length;
      for (let i = 0; i < remainingCells; i++) {
        let emptyCell = document.createElement(td);
        currentRow.appendChild(emptyCell);
      }
    }
    
    this.elem.appendChild(table);
  }
}

// declare a instance of Calendar
const cal = new Calendar(document.getElementById("Calendar"));

// call the display() method
cal.display();

我的 HTML:

<html>

  <head>
  
    <link rel="stylesheet" href="assets/calendar.css">
  
  </head>
  <body>
    <div id="calendar"></div>
    <table>
    
    </table>
  </body>
  <script src="assets/calendar.js"></script>
</html>

我已使用浏览器控制台来确保不存在 JS 错误。

此外,我一直在使用 MDN 的文档资源网页。

我怀疑我有 cal.display 问题或将表附加到 DOM 的问题。

最后,我不一定要寻找简单的解决方案。更多的是一个指南。我很认真地想提高我的前端技能。

提前谢谢您。

javascript html dom domdocument string-concatenation
1个回答
0
投票

他们的

Calendar
功能一开始就是错误的。人们应该使用
Date
对象和
Intl.DateTimeFormat
对象作为处理日期的基础。

就使用

document.createElement
document.createTextNode
以及文档/元素
.appendChild
而言 - 使用起来非常简单。

第 1 步:弄清楚你想要什么。你追求的最终结果是什么?把它画在一张纸上。然后编码。

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.