.append无法点击

时间:2016-03-31 18:37:12

标签: javascript jquery html

简单按钮应该在点击时创建新的<p>元素,但它不起作用,我不确定为什么我将其与我的其他代码进行比较。

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();
}

1 个答案:

答案 0 :(得分:5)

您的代码中存在许多语法错误。如果你纠正它们(如下所示),那么它工作正常。当你编写一个JQuery追加时,你需要放一个&#39;)&#39;在你的论点后。同样,功能需要有一个&#39;}&#39;在他们之后。

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();
});