对象构造函数具有创建输入的方法

Object constructor has method to create input

本文关键字:输入 方法 创建 构造函数 对象      更新时间:2023-09-26

这里是演示:

http://jsfiddle.net/b772ubch/e

正如您所看到的,我有四个输入,当我输入值时,我可以在控制台中检查例如卡路里的量(calcCalories();)。

enter code here

我想做什么?我想向对象构造函数添加一个方法,它在添加新产品的过程中自动将文本输入添加到主体部分,并且这个输入必须是以前输入的sibling。有什么想法吗?

您应该为您的输入创建标签字段。我所做的是更新您的createInput函数以接受产品名称。然后,它处理创建标签、输入和br的所有工作。它为标签填充innerHTML。你走在了正确的轨道上。http://jsfiddle.net/b772ubch/4/

JS

function createInput(name) {
  var input = document.createElement("input");
  var br = document.createElement("br");
  var newlabel = document.createElement("Label");

  input.type = "text";
  input.className = "css-class-name";
  input.setAttribute("id", name);
  
  newlabel.setAttribute("for", name);
  newlabel.innerHTML = "Amount of " + name + " [g]: ";
  
  container.appendChild(newlabel);
  container.appendChild(input);
  container.appendChild(br);
  return input;
}
// Constructor //
function Product(name, calories, protein, fat, carbohydrates) {
  this.name = name;
  this.calories = calories;
  this.protein = protein;
  this.fat = fat;
  this.carbohydrates = carbohydrates;
  createInput(this.name);
}
相关文章: