在对象创建器中向 DOM 添加选项

adding options to DOM in object creator

JSFiddle

我正在尝试制作一个怪物列表,并能够在它们被杀死时赋予它们价值,例如统计数据和资源。我认为最简单的方法是使用对象制造器,但我不确定如何将怪物正确地实现到我的 html 中。我怎样才能让创建的每个新 Monster 对象都将自己添加到 html 中的 select?

function Monster(exp, gold, hp, atk, def, spd) {
    this.exp = exp;
  this.gold = gold;
  this.hp = hp;
  this.atk = atk;
  this.def = def;
  this.spd = spd;
  this.implement = function() {
    var monsterList = document.getElementById('monsterList');
    monsterList.createElement('OPTION');
  }
}

var fly = new Monster(1, 1, 5, 1, 0, 1);
var mouse = new Monster(2, 3, 10, 2, 0, 2);
var rat = new Monster(4, 5, 20, 4, 2, 2);
var rabidChihuahua = new Monster(6, 8, 35, 6, 1, 4);
var bulldog = new Monster(10, 14, 60, 10, 4, 1);

首先,您称为 implement 的方法永远不会执行。其次,createElement 应该在 document 对象下调用。请参阅下面修改的代码,并在此处找到 working JSFiddle:

function Monster(exp, gold, hp, atk, def, spd) {
    this.exp = exp;
  this.gold = gold;
  this.hp = hp;
  this.atk = atk;
  this.def = def;
  this.spd = spd;
  // Method definition
  this.implement = function() {
    var monsterList = document.getElementById('monsterList');
    var opt = document.createElement('OPTION'); // Creating option
    opt.innerText = 'Monster ' + exp; // Setting innertText attribute
    monsterList.appendChild(opt); // appending option to select element
  }
  // Method execution
  this.implement();
}

var fly = new Monster(1, 1, 5, 1, 0, 1);
var mouse = new Monster(2, 3, 10, 2, 0, 2);
var rat = new Monster(4, 5, 20, 4, 2, 2);
var rabidChihuahua = new Monster(6, 8, 35, 6, 1, 4);
var bulldog = new Monster(10, 14, 60, 10, 4, 1);

很简单,但是你需要在 select 标签中显示怪物的名字

currentLvl = 1;
expNeeded = 10;

function Monster(name, exp, gold, hp, atk, def, spd) {
  this.exp = exp;
  this.gold = gold;
  this.hp = hp;
  this.atk = atk;
  this.def = def;
  this.spd = spd;

  //new property
  this.name = name;

  //get html list object
  var monsterList = document.querySelector('#monsterList');

  //create html option object
  var option = document.createElement('option');

  //assign value - will be triggered on selection change
  option.value = this.name;

  //assign display text - just a text to display
  option.textContent = 'Monster ' + this.name;

  //add to monsters list
  monsterList.appendChild(option);
}

var fly = new Monster('fly', 1, 1, 5, 1, 0, 1);
var mouse = new Monster('mouse', 2, 3, 10, 2, 0, 2);
var rat = new Monster('rat', 4, 5, 20, 4, 2, 2);
var rabidChihuahua = new Monster('rabidChihuahua', 6, 8, 35, 6, 1, 4);
var bulldog = new Monster('bulldog', 10, 14, 60, 10, 4, 1);

document.querySelector('#monsterList').onchange = function(event) {
  console.log(event.target.value);
}
<select id="monsterList">

</select>

单击 运行 代码片段按钮查看演示