Mazz Mazz - 9 months ago 38
HTML Question

What's wrong with this jQuery click function?

I'm currently working on a pretty goofy project, just to get a my foot into the door of jQuery. Here's what I've got so far:

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


Sorry about the funky StackOverflow formatting, but my problem is that the click function on
.battleOne
isn't working. Can anyone tell me what I'm doing wrong? Thanks!

Answer Source

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>