2016-03-31 140 views
-1

簡單的按鈕,應該創建新的<p>元素,當它被點擊,但它不工作,我不知道爲什麼,因爲我已經將它與其他代碼進行了比較。.append不起作用點擊

Demo

var battle = function() { 
    while(monsterHP > 0){ 
     var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2); 
     $('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>"); 
     monsterHP -= playerDam; 
     if(monsterHP <= 0) { 
      $('#battle').append("<p>You have defeated the monster</p>"); 
     } 
    } 
} 

$('#battleButton').click(function() { 
    battle(); 
} 
+3

你看過瀏覽器控制檯嗎?有一個語法錯誤。 – Xufox

回答

5

你在你的代碼中的許多語法錯誤。如果你糾正它們(如下),那麼它工作正常。當你寫一個JQuery追加時,你需要在你的參數後面加一個')'。同樣,函數需要在它們後面有一個'}'。

var playerAtk = 5; 
var playerDef = 5; 
var playerHP = 10; 
var monsterAtk = 4; 
var monsterDef = 4; 
var monsterHP = 8; 

var battle = function() { 
    while(monsterHP > 0){ 
     var playerDam = Math.floor(Math.random() * ((playerAtk - monsterAtk) + 2)); 
     $('#battle').append("<p>You have hit the monster for " + playerDam + " damage. The monster has " + (monsterHP - playerDam) + "HP left</p>"); 
     monsterHP -= playerDam; 
     if(monsterHP <= 0) { 
      $('#battle').append("<p>You have defeated the monster</p>"); 
     } 
    } 
} 

$('#battleButton').click(function() { 
    battle(); 
}); 
+2

感謝你在回答之前就明白了這一點,猜測我貼得太倉促了。 – Shniper

+1

@Shniper如果這回答了您的問題,請將其標記爲已回答。 TY –