我目前正在从事一个相当愚蠢的项目,只是想让我步入jQuery之门。到目前为止,这是我得到的:

$("#buyOne").click(function() {
    one++;
    var costOne = 10;
    if (coins - costOne < 0) {
        alert("Dogs ain't free, ya know!");
    } else {
        dogs += 1;
        coins -= costOne;
        $("#main").html("You have " + coins + " coins.");

        var levelOne = $("<div></div>", {
            "class" : "levelOne dog one"+one
        })

        $("body").append(levelOne);

        var battleOne = $("<button class='battleOne'>Send dog to battle</button>");

        $(".one"+one).append(battleOne);
    }
});

$(".battleOne").click(function() {
    coins += 1;
    alert("Your dog won the battle! + 1 coin");
});


对不起时髦的StackOverflow格式,但是我的问题是.battleOne上的click功能无法正常工作。谁能告诉我我在做什么错?谢谢!

最佳答案

var battleOne = $("<button class='battleOne'>Send dog to battle</button>");

$(".one").click(function() {
  $('body').append(battleOne);

});

$(document).on("click",".battleOne",function() {
  alert("Your dog won the battle! + 1 coin");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='one'>add</button>

10-08 07:13