[英]jQuery/JavaScript - passing variables to functions
我有一個看起來像這樣的函數:
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();
}
}
我的變量通過以下方式拋出:
onclick="flee('+currentEnemyHealth+')"
但是當我console.log
或alert()
我得到的都是Undefined
...
我在這里錯過了一個把戲嗎? 我以為,如果我將變量傳遞給函數(在本例中為enemyHealth
),那么我應該能夠檢索它?
謝謝。
PS
只是以為我會聲明,即使我通過該函數傳遞了卡編碼的數字(例如5),它仍然會以Undefined
到達
您確定您不是故意的:
onclick="flee("+currentEnemyHealth+")"
修改引號,以便將currentEnemyHealth的值嵌入到字符串中?
你打電話應該是
onclick="flee(" + currentEnemyHealth + ")"
希望這可以幫助。
currentEnemyHealth不在javascript調用的范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.