我正在尝试制作一份怪物列表,并能够在被杀死时为它们提供诸如统计数据和资源之类的值。我认为最简单的方法是使用对象生成器,但我不确定如何正确地将怪物实现到我的 html 中。我怎样才能使创建的每个新 Monster 对象将其自身添加到 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
的方法永远不会被执行。其次,应该在 document
对象下调用 createElement
。请参阅下面修改的代码,并在此处找到 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);
关于javascript - 在对象创建器中向 DOM 添加选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36043642/