我正在尝试制作一个怪物列表,并且能够在被杀时给予他们诸如统计数据和资源等值。我认为最简单的方法是使用对象制作者,但我不确定如何在我的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);
答案 0 :(得分: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);
答案 1 :(得分:1)
非常简单,但您需要Monster的名称才能在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>
单击“运行代码段”按钮以查看演示