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

adding options to DOM in object creator

本文关键字:DOM 添加 选项 对象 创建      更新时间:2023-09-26

JSFiddle

我正在尝试列出怪物列表,并能够在被杀死时为它们提供属性和资源等值。我认为最简单的方法是使用对象生成器,但我不确定如何将怪物正确实现到我的 html 中。如何使创建的每个新怪物对象都将自身添加到 html 中的选择中?

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对象下调用。请参阅下面修改的代码,并在此处找到一个有效的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>

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