Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

javascript - How does appenchild work in this calendar?

    for (var k = 1; k <= totalDay; k++) {
      var dayTd = document.createElement("td");
      var dayNum = document.createTextNode(k);
      dayTd.appendChild(dayNum);
      weekTr.appendChild(dayTd);
      if ((firstDay + k) % 7 == 0) {
        var weekTr = document.createElement("tr");
      }
      calendar.appendChild(weekTr);
    }

I'm new to JavaScript and try to make a calendar. I try to print days of month out and accidentally find the code write in that way works! Though it prints out the result successfully, I don't really understand how calendar.appendChild(weekTr) in this loop works. I suppose it should be placed outside the loop after saving seven tds in one tr in the loop and then saving it to the table, but it doesn't seem like that. Please refer the code below.

https://jsfiddle.net/cnymd6x5/

question from:https://stackoverflow.com/questions/65905329/how-does-appenchild-work-in-this-calendar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

appendChild removes an element from where it is (if it is anywhere) and then puts it at the end of the thing you are appending it to.

So this:

  1. Puts the TR at the end of the table (assuming it had been created before the loop and wasn't anywhere in the DOM already).
  2. Removes the TR from the end of the table, then puts it back in the same place
  3. Removes the TR from the end of the table, then puts it back in the same place
  4. Removes the TR from the end of the table, then puts it back in the same place
  5. Removes the TR from the end of the table, then puts it back in the same place
  6. Removes the TR from the end of the table, then puts it back in the same place
  7. Removes the TR from the end of the table, then puts it back in the same place

… and then the loop ends.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...