2015-12-12 5 views
1

Я программирую небольшую текстовую игру на основе rpg, и у меня возникла проблема, когда я не знаю, как исправить. Проблема заключается в этой функции и ...Параметр функции не определен - Javascript

function materia(mate, nam) { 
     var matt = mate; 
     console.log(matt); 
     document.getElementById("menu").innerHTML = '<a href="#" onclick="examine(matt)">Examine ' + nam + '</a><a href="#" onclick="take(matt)">Take ' + nam + '</a><br><br><a href="#" onclick="eat(matt)">Eat/Drink ' + nam + '</a><a href="#" onclick="touch(matt)">Touch ' + nam + '</a>'; 
    } 

Эта ссылка на функцию:

var room = ['<a href="#" onclick="materia(0, \'water\')">Water</a> drips from the ceiling into <a href="#" onclick="materia(0,\'pools\')">small, murky pools</a> amongst the <a href="#" onclick="materia(1,\'stone\')"> tiles of stone</a>. The <a href="#" onclick="materia(1,\'brick walls\')">brick walls</a> are covered in <a href="#" onclick="materia(2,\'dark moss\')">dark moss</a> and seem to be slightly concave. <a href="#" onclick="materia(3,\'wood\')">Chunks of wet, termite infested wooden two by fours</a> lay on the ground.', 

По какой-то причине, когда я вызываю функцию изучить и передать переменную матовую через, он говорит, что матовые не определено. Однако в консольном журнале говорится, что матовый равен 0. Это происходит, когда я исследую подземелье, пока не доберусь до комнаты с водой и не нажму на первую ссылку под названием вода. Я понятия не имею, что случилось, но может быть, кто-то здесь. Сохраняет весь код, если проблема лежит где-то в другом месте.

<html> 
<body> 
<p id='main'></> 
<p id='menu'></p> 
<p id='footer'></p> 
<script> 

function entity(hp, mp, body, mind, soul, name, gear, gp, statPts, lvl, xp, powers, def) { 
    this.hp = hp; 
    this.mp = mp; 
    this.body = body; 
    this.mind = mind; 
    this.soul = soul; 
    this.name = name; 
    this.gear = gear; 
    this.gp = gp; 
    this.statPts = statPts; 
    this.lvl = lvl; 
    this.xp = xp; 
    this.powers = powers; 
    this.def = def; 
} 

var player = new entity(5, 5, 5, 5, 5, "DJ Khaled", ["Satchel", "Linen Shirt", "Plaid Boxers", "Leather Pants"], 100, 5, 1, 0, 0, 0); 
var goblin = new entity(5, 5, 2, 2, 2, "Goblin", ["Pike", "Steel Buckler", "Leather Cap", "Snakeskin Banana Hammock"], 23, 0, 1, 14, 0, 0); 

function startMenu() { 
    document.getElementById("main").style.textAlign = "center"; 
    document.getElementById("footer").style.textAlign = "center"; 
    document.getElementById("menu").style.textAlign = "center"; 
    document.getElementById("main").innerHTML ='Adventurama<br><br><a href="#" onclick="playGame()">Play</a>'; 
} 

function playGame() { 
    document.getElementById("main").innerHTML = 'Enter name:<br><input id="charName"></input><button onclick="genChar()">Enter</button>'; 
} 

function genChar() { 
    player.name = document.getElementById("charName").value; 
    genChar2(); 
} 

function genChar2() { 
    document.getElementById("main").innerHTML = player.name + ' <br>Allocate your stats:<br><br>Body ' + player.body + ' <button onclick="statAlloc(1)">+</button> <button onclick="statAllocM(1)">-</button><br><br> Mind ' + player.mind + ' <button onclick="statAlloc(2)">+</button> <button onclick="statAllocM(2)">-</button><br><br> Soul ' + player.soul + ' <button onclick="statAlloc(3)">+</button> <button onclick="statAllocM(3)">-</button><br><br> Stat Points Left: ' + player.statPts + '<br><br><button onclick="mainGame()">Continue</button>'; 
} 

function statAlloc(a) { 
    if (player.statPts <= 0) { 
    genChar2(); 
    } else { 
    switch (a) { 
     case 1: 
     player.body += 1; 
     player.statPts -= 1; 
     break; 
     case 2: 
     player.mind += 1; 
     player.statPts -= 1; 
     break; 
     case 3: 
     player.soul += 1; 
     player.statPts -= 1; 
     break; 
     } 
    } 
    genChar2(); 
} 

function statAllocM(a) { 
    switch (a) { 
    case 1: 
     player.body -= 1; 
     player.statPts += 1; 
     break; 
    case 2: 
     player.mind -= 1; 
     player.statPts += 1; 
     break; 
    case 3: 
     player.soul -= 1; 
     player.statPts += 1; 
     break; 
    } 
    genChar2(); 
} 

function mainGame() { 
    document.getElementById("main").innerHTML = '<a href="#" onclick="dungeon(-1)">Explore the Dungeons</a><br><br><a href="#" onclick="shop()">Buy some Gear</a><br><br><a href="#" onclick="city()">Explore the City</a><br><br><a href="#" onclick="character()">View your Character</a><br><br><a href="#" onclick="inventory()">Check your Inventory</a>'; 
    document.getElementById("footer").innerHTML = ''; 
} 

var prevRoom = -1; 

function dungeon(z) { 
    var room = ['<a href="#" onclick="materia(0, \'water\')">Water</a> drips from the ceiling into <a href="#" onclick="materia(0,\'pools\')">small, murky pools</a> amongst the <a href="#" onclick="materia(1,\'stone\')"> tiles of stone</a>. The <a href="#" onclick="materia(1,\'brick walls\')">brick walls</a> are covered in <a href="#" onclick="materia(2,\'dark moss\')">dark moss</a> and seem to be slightly concave. <a href="#" onclick="materia(3,\'wood\')">Chunks of wet, termite infested wooden two by fours</a> lay on the ground.', 
       'The <a href="#" onclick="materia(1,\'stone bricks\')"> stone bricks and tiles</a> fade away into a cave full of <a href="#" onclick="materia(4,\'stalagmites\')">stalagmites</a>. In every nook and cranny, red flickering <a href="#" onclick="materia(5,\'candles\')">red, flickering candles</a> slowly melt away. The walls are covered in noir style artwork of monstrous beasts, rape, demons, and dismembered limbs. In the center of the room there is a <a href="#" onclick="materia(1,\'stone\')">large slab of stone</a> with a pile of bloodstained oriental robes.', 
       'Cracked marble tiles crawl forward alongside giant pillars that escalate beyond the farthest reaches of your eyesight. At the end of this corridor, two giant statues of godly figures pose in an eternal state of magnificence and glory.', 
       'The entirery of this room has been sculpted into a jade dragon, coiled up and sleeping. The room is fairly small only being about twelve feet in diameter. From a pinhole in the ceiling, a trail of light streams down upon a stone altar, fixed onto the floor.', 
       'Long lines of wooden bookcases containing hundreds of dusty leather tomes fill the cobweb ridden stone room. Stairs on all sides of the room lead to a wooden overhang with iron rails. A red pentogram on the ceiling drips fresh blood on the wood floor.' 
      ]; 
    do { 
    var ran = Math.floor(Math.random() * room.length); 
    } while (ran == prevRoom) 
    prevRoom = ran; 
    if (z > -1) { 
    document.getElementById("main"). innerHTML = room[z]; 
    } else { 
    document.getElementById("main"). innerHTML = room[ran]; 
    } 
    document.getElementById("menu"). innerHTML = ''; 
    document.getElementById("footer").innerHTML = '<br><a href="#" onclick="dungeon()">Keep Exploring</a><br><a href="#" onclick="mainGame()">Leave</a>'; 

} 

/* 
Actions: 
    kick, punch, talk, open, 
    close, examine, take, give, 
    throw, eat, touch 
Materials: 
    0: water, 1: stone, 2: moss, 3: wood 
    4: stalagite, 5: candle, 6: robes 
    7: marble, 8: god statue, 9: jade 
    10: altar, 11: bookcase, 12: 
    13: iron rail, 14: blood, 15: debris 
*/ 

function materia(mate, nam) { 
    var matt = mate; 
    document.getElementById("menu").innerHTML = '<a href="#" onclick="examine(matt)">Examine ' + nam + '</a><a href="#" onclick="take(matt)">Take ' + nam + '</a><br><br><a href="#" onclick="eat(matt)">Eat/Drink ' + nam + '</a><a href="#" onclick="touch(matt)">Touch ' + nam + '</a>'; 
} 

function examine(mate) { 
    var exam = ['You examine the water. The water is ordinary water save for a <a href="#" onclick="materia(15,\'dirt\')">miniscule amount of debris</a> floating around.', 
         'You examin the stone. Weathered and rough and greyish blue in hue, this is some fine stone.', 
         'You examine the moss. It is fairly damp and a deep foresty green. It is very soft.', 
         'You examine the wood. It is slightly coarse and grainy, somewhat splintery around the edges. It is a tannish, sandy color.', 
         'You examine the stalagmite. Bearing the resembelance of a mineral icicle, the stalagmite is rough, ivory and pretty pointy.', 
         'You examine the candle. It is somewhat stubby with lots of buildup melted wax around the top. Protruding from the top is a black wick.', 
         'You examine the robes. They are silky and flowy and the fabric is very thin. The white hems are very large and the rest of the material is decorated with beautiful art.', 
         'You examine the marble. The marble is so smooth, you can see a faint glossy reflection of yourself in it. It is a creamy white color with faint dark swirls.', 
         'You examine the statue. A nude, godly figure of exquisite physique has been depicted from this slab of marble. It stands about 10 feet tall.' 
         ]; 
    document.getElementById("menu").innerHTML = exam[mate]; 
} 

function matt() { 
    var n=0; 
} 

startMenu(); 











</script> 
</body> 
</html> 
+0

Ну, 'matt' есть * локальный * функционировать' Материя ', поэтому, когда нажата кнопка привязки,' matt' не может быть найден, и поэтому 'undefined' передается' exam'. –

+0

Не используйте атрибуты onclick. Правильно использовать события (http://quirksmode.org/js/introevents.html). – Bergi

ответ

0

Проблема заключается в том, что матовый только получает оценку, когда пользователь нажимает на ссылку, а затем контекст уже не функция Материя, но глобальный масштаб. Как и в этой области matt - это функция (ср. Конец вашего скрипта), вы передаете ссылку функции вместо численного значения.

Быстрых затруднительный, чтобы вставить фактическое значение матовой в анкерных элементах добавляемых в йот, как это:

function materia(mate, nam) { 
    var matt = mate; 
    console.log(matt); 
    document.getElementById("menu").innerHTML = 
     '<a href="#" onclick="examine(' + matt + ')">Examine ' + nam + 
     '</a><a href="#" onclick="take(' + matt + ')">Take ' + nam + 
     '</a><br><br><a href="#" onclick="eat(' + matt + ')">Eat/Drink ' + nam + 
     '</a><a href="#" onclick="touch(' + matt + ')">Touch ' + nam + '</a>'; 
} 
Смежные вопросы