将标签添加到动态创建的HTML输入

时间:2013-07-22 17:27:08

标签: javascript html

我认为我对使用javascript创建动态HTML元素的基本理解缺少了一些东西。在尝试了许多我在网上找到类似问题的例子后,我决定发布我的问题。我有一个JS函数,动态创建三个输入表单,但我想标记每个输入框。

function newItem(){
  instance++;

  var oldInput = document.getElementById("itemInfo");
  var parent = oldInput.parentNode;
  var newDiv = document.createElement("div");

  var item = document.createElement("INPUT");
  var qty = document.createElement("INPUT");
  var color = document.createElement("INPUT");

   item.name = "item" + instance;
  item.value = "Enter Item";
  qty.name = "qty" + instance;
  qty.value = "Enter Qty";
  color.name = "color" + instance;
  color.value = "Enter Color";
  newDiv.appendChild(item);
  newDiv.appendChild(qty);
  newDiv.appendChild(color);

  p = qty.parentNode;

  var itemLabel = document.createElement("Label");
    itemLabel.setAttribute("for", item);
    itemLabel.innerHTML = "Item: ";
  newDiv.insertBefore(itemLabel, item);
  var qtyLabel = document.createElement("Label");
    qtyLabel.setAttribute("for", qty);
    qtyLabel.innerHTML = "Qty: ");
  document.body.appendChild(qtyLabel, qty);
   var colorLabel = document.createElement("Label");
     colorLabel.setAttribute("for", color);
     colorLabel.innerHTML = "Color: ");
   color.appendChild(colorLabel);



  parent.insertBefore(newDiv, oldInput);

}

如果我按如下方式注释,我只能正确地输入第一个输入框:

var itemLabel = document.createElement("Label");
    itemLabel.setAttribute("for", item);
    itemLabel.innerHTML = "Item: ";
  newDiv.insertBefore(itemLabel, item);
  // var qtyLabel = document.createElement("Label");
  //   qtyLabel.setAttribute("for", qty);
  //   qtyLabel.innerHTML = "Qty: ");
  // document.body.appendChild(qtyLabel, qty);
  // var colorLabel = document.createElement("Label");
  //   colorLabel.setAttribute("for", color);
  //   colorLabel.innerHTML = "Color: ");
  // color.appendChild(colorLabel);

但是,如果我在尝试标记第二个和第三个输入框时取消注释底部两个中的任何一个,则单击带有newItem()函数操作的按钮不会创建任何其他输入表单。如何使用各自的标签动态创建表单?

1 个答案:

答案 0 :(得分:5)

这些行有语法错误:

qtyLabel.innerHTML = "Qty: ");
colorLabel.innerHTML = "Color: ");

改为:

qtyLabel.innerHTML = "Qty: ";
colorLabel.innerHTML = "Color: ";

也许正因为如此,当你评论它们时它会起作用。

相关问题