如何在JavaScript中的for循环中创建一个元素

时间:2018-01-17 02:34:52

标签: javascript dom clock

注意:请查看代码结构。您无法将节点附加到数组,就像您可以“.pop”或“删除节点中的项目一样。”

我试图在for循环中创建一个元素,或者forEach(尝试两者)。

我获取了值,但它们是在一个数组中。

因此它们嵌套在ul中,但它们没有li标签。

我尝试添加li标签,但我无法实现。

以下是codepen:https://codepen.io/Aurelian/pen/opaxqx?editors=1010

以下是代码:

    // Get te location
// Make the : blink

//var location = document.querySelector('.clock-location');

function abbrev(a,b) {
  return a.substr(0,b);
}

function currentDay() {
  // Go to array
  // If today day (number) matched one of the array
  // To this add active
}

function displayTime() {

  var clockTime = document.querySelector('.clock-time');
  var clockDay = document.querySelector('.clock-day');
  var clockWeekdays = document.querySelector('.clock-weekdays');

  var date = new Date();

  var weekday = new Array(7);
  weekday[0] = "Monday";
  weekday[1] = "Tuesday";
  weekday[2] = "Wednesday";
  weekday[3] = "Thursday";
  weekday[4] = "Friday";
  weekday[5] = "Saturday";
  weekday[6] =  "Sunday";

  var singleDay = [];

  // weekday.forEach(function(day){
  //  singleDay.push(abbrev(day,3));
  // });

  for (var i = 0; i < weekday.length; i++) {
    var day = weekday[i];
    var li = document.createElement('li').innerHTML = day;
    singleDay.push(abbrev(li,3));
  }

  // Mechanics
  var todayDay = weekday[date.getDay()];

  // Display
  clockDay.innerHTML = abbrev(todayDay,3);
  clockWeekdays.innerHTML = singleDay;

  setTimeout(startTime, 1000);
}



displayTime();

// Get the time

//Loop Throw weekdays - show 3 letters

3 个答案:

答案 0 :(得分:1)

我已经稍微改变了你的循环(删除了push步骤,并且每次循环迭代都会追加新的子句):

for (var i = 0; i < weekday.length; i++) {
  var day = weekday[i];
  var li = document.createElement('li');
  li.innerHTML = abbrev(day,3);
  clockWeekdays.appendChild(li);
}

不要忘记评论/删除此行:

clockWeekdays.innerHTML = singleDay;

否则您的innerHTML将被覆盖。这是工作的代码:

https://codepen.io/commercialsuicide/pen/WdaojM?editors=1010

答案 1 :(得分:0)

在你的for循环中,去掉你将li推入数组的最后一行,而是使用appendChild()将新创建的li元素添加到

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

答案 2 :(得分:0)

您需要正确创建元素,然后使用>>> a = [ (2, 6) , (1,3) , (0,2) ] >>> min(a, key=sum) (0, 2) >>> a = [ (2, 6) , (1,3) , (0,7) ] >>> min(a, key=sum) (1, 3)

appendChild