CreateElement,然后编写innerHTML

时间:2018-08-21 07:52:10

标签: javascript html dom

所以我已经搜索了2天了。有人将如何创建元素,然后使用innerHTML用HTML编写元素?

function dataPull() {
      // Connects to my server from which it pulls JSON data containing start,end,summary,organizer of the event.
      fetch("http://localhost:8000/events").then((resp) => resp.json()).then(render)
    };

    function eventFilter(event) {
      eventTime = new Date(event);
      eventHours = eventTime.getHours();
      eventMinutes = eventTime.getMinutes();
      if (eventMinutes < 10) {
        eventMinutes = "0" + eventMinutes
      }
      return event = eventHours + ":" + eventMinutes;
    };

    function eventMap(eventBooked) {
      return `
        <div class="event">
            <div class="eventTime">${eventFilter(eventBooked.start)}
                <p class="timep">${eventFilter(eventBooked.end)}</p>
            </div>
            <div class="eventInfo">
                <h1 class="eventSummary"> ${eventBooked.summary}</h1>
                <p class="eventOrganizer">${eventBooked.organizer}</p>
            </div>
        </div>`;
    };

    function render(data) {
      data.events.sort(function(a, b) {
        return new Date(a.start).getTime() - new Date(b.start).getTime();
      });

      // Delete outdated events.
      let eventsNotOutdated = data.events.filter((item) => {
        let endTime = new Date(item.end);
        if (Date.now() < endTime) {
          return item;
        }
      });

      // Create a new variable for event currently in progress.
      let eventInProgress = eventsNotOutdated.filter((item) => {
        let startTime = new Date(item.start);
        if (Date.now() > startTime) {
          return item;
        }
      });

      // Same as eventsNotOutdated but without the event in progress.
      let filteredEventsNotOutdated = eventsNotOutdated.filter((item) => {
        let startTime = new Date(item.start);
        if (Date.now() < startTime) {
          return item;
        }
      });

      if (eventInProgress.length > 0 && filteredEventsNotOutdated.length >= 1) {
        return document.getElementById("eventList").innerHTML =
          `<div>
            <h1 class="announcerBig">In progress</h1>
            <div class="eventBig">
              <div class="eventTimeBig">${eventFilter(eventInProgress[0].start)}
              <p class=timep>${eventFilter(eventInProgress[0].end)}</p>
            </div>
            <div class="eventInfoBig">
              <h1 class="eventSummaryBig">${eventInProgress[0].summary}</h1>
              <p class="eventOrganizerBig">${eventInProgress[0].organizer}</p>
            </div>
           </div>
            </div>
            <div class=eventsInProgress>
            <h1 class="announcer">Later</h1>${filteredEventsNotOutdated.map(eventMap).join("")}
            </div>`;
      } else if (eventInProgress.length > 0 && filteredEventsNotOutdated.length < 1) {
        return doc.getElementById("eventList").innerHTML =
          `<div>
            <h1 class="announcerBig">In progress</h1>
            <div class="eventBig">
              <div class="eventTimeBig">${eventFilter(eventInProgress[0].start)}
                <p class=timep>${eventFilter(eventInProgress[0].end)}</p>
              </div>
              <div class="eventInfoBig">
                <h1 class="eventSummaryBig">${eventInProgress[0].summary}</h1>
                <p class="eventOrganizerBig">${eventInProgress[0].organizer}</p>
              </div>
           </div>`
      } else if (eventInProgress.length === 0 && filteredEventsNotOutdated.length > 0) {
        return document.getElementById("eventList").innerHTML =
          `<h1 class="announcerBig">Coming up next</h1>${filteredEventsNotOutdated.map(eventMap).join("")}`;
      } else {
        document.getElementById("eventList").innerHTML =
          `<p class="noevent">No meetings scheduled.</p><p class="schedule">Schedule meetings on google calendars.`;
      };
    };

    setTimeout(dataPull);
    setInterval(dataPull, 10000);
<html>

<head>
</head>

<body id='body'>
  <div id='eventList' class="eventList"></div>
  <script src="example.js"></script>
</body>

</html>

这是我正在使用的代码的快速演示。如您所见,我没有使用任何document.createElement方法,但是如果我没有使用backtic,我会使用createElement。我试过了,但问题是,每隔10秒(由于间隔),它就会调用该函数并不断地写入相同的元素。注意:由于我要提取的数据正在不断更新,因此需要间隔时间,因此我需要在显示器上进行不断更新。

现在我的问题是: 是否可以使用innerHTML方法在HTML中编写带有附加子元素的已创建元素?

1 个答案:

答案 0 :(得分:0)

您有使用document.createElement的代码段,它应该像您的版本一样工作(如果在IE上,您可能需要将textContent替换为innerText

function dataPull() {
  // Connects to my server from which it pulls JSON data containing start,end,summary,organizer of the event.
  fetch("http://localhost:8000/events").then((resp) => resp.json()).then(render)
};

function eventFilter(event) {
  eventTime = new Date(event);
  eventHours = eventTime.getHours();
  eventMinutes = eventTime.getMinutes();
  if (eventMinutes < 10) {
    eventMinutes = "0" + eventMinutes
  }
  return eventHours + ":" + eventMinutes;
};

function eventMap(eventBooked, classSuffix = "") {
  event = document.createElement("div")
  event.classList.add("event")

  // create time
  time = document.createElement("div")
  time.classList.add("eventTime" + classSuffix)
  time.textContent = eventFilter(eventBooked.start)
  // create timep
  timep = document.createElement("p")
  timep.classList.add("timep")
  timep.textContent = eventFilter(eventBooked.end)

  // create info
  info = document.createElement("div")
  info.classList.add(eventTime)
  // create summary
  summary = document.createElement("h1")
  summary.classList.add("eventSummary" + classSuffix)
  summary.textContent = eventBooked.summary
  // create organizer
  organizer = document.createElement("p")
  organizer.classList.add("eventOrganizer" + classSuffix)
  organizer.textContent = eventBooked.organizer

  // append everything
  event.appendChild(time)
  time.appendChild(timep)

  event.appendChild(info)
  info.appendChild(summary)
  info.appendChild(organizer)

  return event
};

function render(data) {
  data.events.sort(function(a, b) {
    return new Date(a.start).getTime() - new Date(b.start).getTime();
  });

  // Delete outdated events.
  let eventsNotOutdated = data.events.filter((item) => {
    let endTime = new Date(item.end);
    if (Date.now() < endTime) {
      return item;
    }
  });

  // Create a new variable for event currently in progress.
  let eventInProgress = eventsNotOutdated.filter((item) => {
    let startTime = new Date(item.start);
    if (Date.now() > startTime) {
      return item;
    }
  });

  // Same as eventsNotOutdated but without the event in progress.
  let filteredEventsNotOutdated = eventsNotOutdated.filter((item) => {
    let startTime = new Date(item.start);
    if (Date.now() < startTime) {
      return item;
    }
  });

  let eventList = document.getElementById("eventList");
  for(let child of eventList.children) {eventList.removeChild(child)}

  if (eventInProgress.length > 0) {
    div = document.createElement("div")
    
    announcerBig = document.createElement("h1")
    announcerBig.classList.add("announcerBig")
    announcerBig.textContent = "In progress"
    
    eventBig = eventMap(eventInProgress[0], "Big")
    
    div.appendChild(announcerBig)
    div.appendChild(eventBig)
    
    eventList.appendChild(div)
    
    if (filteredEventsNotOutdated.length) {
      inProgress = document.createElement("div")
      
      announcer = document.createElement("h1")
      announcer.classList.add("announcer")
      announcer.textContent = "Later"
      
      inProgress.appendChild(announcer)
      
      filteredEventsNotOutdated.forEach(ev => {eventList.appendChild(eventMap(ev))})
      
      eventList.appendChild(inProgress)
    }
    
  } else if (eventInProgress.length === 0 && filteredEventsNotOutdated.length > 0) {
      announcerBig = document.createElement("h1")
      announcerBig.classList.add("announcerBig")
      announcerBig.textContent = "Coming up next"
      
      eventList.appendChild(announcerBig)
      
      filteredEventsNotOutdated.forEach(ev => {eventList.appendChild(eventMap(ev))})
  } else {      
      noevent = document.createElement("p")
      noevent.classList.add("noevent")
      noevent.textContent = "No meetings scheduled."
      
      schedule = document.createElement("p")
      schedule.classList.add("schedule")
      schedule.textContent = "Schedule meetings on google calendars."
      
      eventList.appendChild(noevent)
      eventList.appendChild(schedule)
  };

  return eventList
};

setTimeout(dataPull);
setInterval(dataPull, 10000);
<html>

<head>
</head>

<body id='body'>
  <div id='eventList' class="eventList"></div>
  <script src="example.js"></script>
</body>

</html>

希望我没有忘记一部分:p

可以轻松进行改进,例如:

  • 在事件未过期时保留事件div(仅删除过期的子项/仅创建新的子项)
  • 在没有正在进行的事件/根本没有任何事件的情况下,查看HTML / CSS以保持相同的状态。

编辑:该行的说明

filteredEventsNotOutdated.forEach(ev => {eventList.appendChild(eventMap(ev))})

可以发展成

for (let ev of filteredEventsNotOutdated) {
    child = eventMap(ev)
    eventList.appendChild(child)
})

查看for...of的文档