Javascript为每个新元素添加新的订单ID

时间:2016-01-07 14:26:42

标签: javascript oop

对不起我的英语我真的不知道如何纠正这个问题!!

我有任务列表,当我添加新任务时,我会为每个新任务添加像序号一样的东西

示例任务1已存储到var whit id 1,Task 2 var id 2 ..... 我想我需要使用迭代但是如何...? Project link

var toDoList = function() {

  var addNewTask = function() {
      var input = document.getElementById("taks-input").value,
        itemTexts = input,
        colA = document.getElementById('task-col-a').children.length,
        colB = document.getElementById('task-col-b').children.length,
        taskBoks = document.createElement("div");

      taskBoks.className = "min-box";

      taskBoks.innerHTML = '<div class="col-3 chack" id=""><i class="fa fa-star"></i></div><div class="col-8 task-text" id="taskContent"><p>' + itemTexts + '</p></div><div class="col-1 color"></div>'

      if (colB > colA) {
        var todolist = document.getElementById("task-col-a");
      } else {
        var todolist = document.getElementById("task-col-b");
      }
      todolist.appendChild(taskBoks);
    },

    addButton = function() {
      var btn2 = document.getElementById("add-task-box");
      btn2.onclick = addNewTask;
    }

  addButton()
};

toDoList();

1 个答案:

答案 0 :(得分:0)

只需使用id="task_' + (taskCount++) + '"

即可
var toDoList = function() {
  var taskCount = 0

  var addNewTask = function() {
      var input = document.getElementById("taks-input").value,
        itemTexts = input,
        colA = document.getElementById('task-col-a').children.length,
        colB = document.getElementById('task-col-b').children.length,
        taskBoks = document.createElement("div");

      taskBoks.className = "min-box";

      taskBoks.innerHTML = '<div class="col-3 chack" id="task_'+(taskCount ++)+'"><i class="fa fa-star"></i></div><div class="col-8 task-text" id="taskContent"><p>' + itemTexts + '</p></div><div class="col-1 color"></div>'

      if (colB > colA) {
        var todolist = document.getElementById("task-col-a");
      } else {
        var todolist = document.getElementById("task-col-b");
      }
      todolist.appendChild(taskBoks);
    },

    addButton = function() {
      var btn2 = document.getElementById("add-task-box");
      btn2.onclick = addNewTask;
    }

  addButton()
};

toDoList();