views:

40

answers:

3

Hello there, I have a function that looks like so:

window.attack = function(enemyHealth){ 
        attackChance = Math.floor(Math.random()*11);
        console.log("enemyHealth: "+enemyHealth); //undefined...
        if (attackChance < 5) { //hit
            hitDamage = Math.floor(Math.random()*playerDamage+1);
            enemyHealth = enemyHealth - hitDamage;
            $('#enemyhealth').val(enemyHealth);
            if (enemyHealth < 1) {
                alert('You killed the '+currentEnemy);
                removeOverlayNow();
            }
        } else if (attackChance >= 5) { //miss
            hitDamage = Math.floor(Math.random()*maxDamage+1); 
            alert('You miss and get attacked for '+hitDamage);
            health = health - hitDamage; 
            $(healthDisplay).val(health); 
            checkHealth(); 
        }
    }

And my variable is being thrown in via:

onclick="flee('+currentEnemyHealth+')"

But when I console.log or alert() all I get is Undefined...

Am I missing a trick here? I thought that if I pass a variable into the function (in this case enemyHealth), that I should be able to retrieve it?

Thanks.

p.s.
Just thought I would state that even if I pass a card-coded number (such as 5) through the function - it still arrives as Undefined

A: 

Are you sure you don't mean:

onclick="flee("+currentEnemyHealth+")"

Fixing the quoting so that the value of currentEnemyHealth is embedded into the string?

qor72
A: 

currentEnemyHealth is not in the scope of the javascript calls.

Thierry-Dimitri Roy
+1  A: 

You call should be

onclick="flee(" + currentEnemyHealth + ")"

Hope this helps.

Ash Burlaczenko
d'oh - don't say a word.
Neurofluxation
Common mistake. Blame it on a hard day at work.
Ash Burlaczenko