首页 > 解决方案 > 动态创建的元素

问题描述

所以我正在尝试创建一个费用跟踪器,其中包含动态创建的选项列表。

用户将能够:

除了我想显示类别以及为每个类别预算的总金额外,我一切正常。

现在我有9个类别。如果一个用途有 2 项具有相同类别的费用,例如"Health & Fitness"DIV ,我希望该类别显示在显示预算总额的左侧。如果还有其他类别,例如“汽车和运输”,我希望它与预算总额一起显示。我似乎无法弄清楚如何根据所选类别来区分总数。

var addListItem = document.getElementById("add-more");

addListItem.addEventListener("click", function() {
  createNewItem();
});

//Display Month and Day
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;

today = mm + "/" + dd;
document.getElementById("current-date").innerHTML = today;

//Creates new elements
function createNewItem() {
  var u = document.getElementById("full-item-list");
  var l = document.createElement("li");
  var elinput = document.createElement('input');
  var select = document.createElement('select');
  var option1 = document.createElement('option');
  var option2 = document.createElement('option');
  var option3 = document.createElement('option');
  var option4 = document.createElement('option');
  var option5 = document.createElement('option');
  var option6 = document.createElement('option');
  var option7 = document.createElement('option');
  var option8 = document.createElement('option');
  var option9 = document.createElement('option');
  var option10 = document.createElement('option');
  var o1 = document.createTextNode('Category');
  var o2 = document.createTextNode('Auto & Transport');
  var o3 = document.createTextNode('Bills & Utilities');
  var o4 = document.createTextNode('Health & Fitness');
  var o5 = document.createTextNode('Home');
  var o6 = document.createTextNode('Personal Care');
  var o7 = document.createTextNode('Pets');
  var o8 = document.createTextNode('Shopping');
  var o9 = document.createTextNode('Entertainment');
  var o10 = document.createTextNode('Investments');
  var expenseName = document.createElement('input');
  var icon = document.createElement('img');

  option1.setAttribute('disabled', 'true');
  option1.setAttribute('selected', 'true');

  option1.appendChild(o1);
  option2.appendChild(o2);
  option2.setAttribute('name', 'testName');
  option3.appendChild(o3);
  option3.setAttribute('name', 'testName2');
  option4.appendChild(o4);
  option5.appendChild(o5);
  option6.appendChild(o6);
  option7.appendChild(o7);
  option8.appendChild(o8);
  option9.appendChild(o9);
  option10.appendChild(o10);

  select.setAttribute('type', 'select');
  select.setAttribute('placeholder', 'Select a Category');
  select.appendChild(option1);
  select.appendChild(option2);
  select.appendChild(option3);
  select.appendChild(option4);
  select.appendChild(option5);
  select.appendChild(option6);
  select.appendChild(option7);
  select.appendChild(option8);
  select.appendChild(option9);
  select.appendChild(option10);

  expenseName.setAttribute('type', 'text');
  expenseName.setAttribute('placeholder', 'Expense name');
  expenseName.setAttribute('class', 'expense-input-name')
  expenseName.setAttribute('name', 'totalExpense');

  elinput.setAttribute('type', 'number');
  elinput.setAttribute('class', 'li-input');
  elinput.setAttribute('placeholder', 'Enter amount');
  elinput.setAttribute('name', 'qty');

  l.setAttribute('class', 'list-item');
  l.setAttribute('name', 'li-name');
  icon.setAttribute('class', 'remove-icon');
  icon.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/375261/System_Delete.ico');
  icon.setAttribute("id", "icon-id");
  icon.addEventListener('click', function(e) {
  thaticon(e);
    }, false);

  l.appendChild(select);
  l.appendChild(expenseName);
  l.appendChild(elinput);
  l.appendChild(icon);
  u.appendChild(l);
}

//Deletes elements
function thaticon(e) {
  console.log("test");
  var el = e.target;
  var elListItem= el.parentNode;
  elFullList = elListItem.parentNode;
  elFullList.removeChild(elListItem);
}

//Calculates and displays results
function displayResult() {
  var arr = document.getElementsByName("qty");
  var wage = document.getElementById("inputWage").value;
  var jumboDiv = document.getElementById("jumbo-results").style.display="block";
  var tot = 0;
  for (var i = 0; i < arr.length; i++) {
    if (parseFloat(arr[i].value)) tot += parseFloat(arr[i].value);
  }
  document.getElementById("result").innerHTML = "Total Expenses: $" + tot.toFixed(2);
  document.getElementById("left").innerHTML = "Left Over: $" + ((wage - tot).toFixed(2));
}

//Resets and clears entire entry
function resetForm() {
  var jumboDiv = document.getElementById("jumbo-results").style.display="none";
  document.getElementById("full-item-list").innerHTML = "";
  document.getElementById("inputWage").value = "";
  document.getElementById("result").innerHTML = "";
  document.getElementById("left").innerHTML = "";
  document.getElementById("number-display").innerHTML = "";
}

//Displays the selected categories by user with the total sum for each one
function displayCategory() {

}

//Capture screen shots
/*function captureScreen() {
  html2canvas(document.querySelector("#capture")).then(canvas => {
      document.body.appendChild(canvas)
  });
}*/

标签: javascriptdynamically-generated

解决方案


您将需要创建一个数据结构来存储类别信息并使用它来构建您的 HTML 元素。

以下代码构造了一个select没有任何附加属性的简单元素。

var optionsArray = ['Category',
                    'Auto & Transport', 
                    'Bills & Utilities',
                    'Health & Fitness',
                    'Home',
                    'Personal Care',
                    'Pets',
                    'Shopping',
                    'Entertainment',
                    'Investments'];

var selectElem = document.createElement('select');
selectElem.setAttribute('placeholder', 'Select a Category');
// iterate through the array of options
optionsArray.forEach(function(text){
  var option = document.createElement('option');
  var optionText = document.createTextNode(text);
  option.appendChild(optionText);
  selectElem.appendChild(option);
});
// selectElem is ready to append to the DOM

这可以通过将数组中的元素更改为对象并在需要时使用属性来改进。

例如

var optionsArray = ['Category',
                    'Auto & Transport', 
                    {
                      'itemText' : 'Bills & Utilities',
                      'itemDisabled' : true,
                      'itemSelected' : true
                    },
                    'Health & Fitness',
                    'Home',
                    'Personal Care',
                    'Pets',
                    'Shopping',
                    'Entertainment',
                    'Investments'];

var selectElem = document.createElement('select');
selectElem.setAttribute('placeholder', 'Select a Category');
// iterate through the array of options
optionsArray.forEach(function(item){
  var text = (typeof(item) === 'string') ? item : item.itemText;
  var option = document.createElement('option');
  var optionText = document.createTextNode(text);
  option.appendChild(optionText);
  if (typeof(item) === 'object') {
    // handle custom attributes
    Object.keys(item).forEach(function(key){
      switch(key) {
        case 'itemDisabled' :
          if (item[key]) {
            option.setAttribute('disabled', true);
          }
          break;
        case 'itemSelected' :
          if (item[key]) {
            option.setAttribute('selected', true);
          }
          break;
        default:
          break;
      }
    });
  }
  selectElem.appendChild(option);
});
// selectElem is ready to append to the DOM

类别总数的计算需要使用诸如对象数组之类的数据结构来完成。遍历数组,在将所需信息添加到 HTML 之前计算总数。


推荐阅读