我正在尝试使痣的图像可点击,点击后分数会增加,但 .on() 将无法与图像的类名一起使用。但是,如果我使用选择器“#gamespace”,它会起作用,但是点击游戏空间内的任何地方都会获得玩家点数,而不仅仅是点击地鼠。
<!DOCTYPE html>
<html>
<head>
<title>Whack-A-Mole (CSCI2447)</title>
<!-- CSS styles: This is for me to worry about; not you. -->
<link href="css/game.css" rel="stylesheet" />
<script src="js/jquery-2.2.1.min.js"></script>
<script type="text/javascript">
var score = 0
var time = 30
var t;
var moleRepeat;
$(document).ready(function(){
$('#start_button').click(function (){
start();
});
$('.mole').on('click' , function () {
counter();
});
});
function getYRandomNumber(){
return Math.floor((Math.random()*300)+0);
};
function getXRandomNumber(){
return Math.floor((Math.random()*600)+0);
};
function counter() {
score++;
$("#score").html(score + ' pts');
};
function start() {
$('#timer').show();
addMole();
decrement();
$('h1').css("color","purple");
$('#gamespace').css("background-color", "green");
};
function decrement() {
time--;
$('#timer').html(time + ' seconds left');
t = setTimeout('decrement()', 1000);
};
function addMole() {
$('#gamespace').append('<img class="mole" src="img/mole.png" onClick="counter()"/>');
moleRepeat = setTimeout('addMole()', 2000);
};
</script>
</head>
<body>
<div id="content">
<h1>Whack-A-Mole</h1>
<p>After clicking "start", you will have 30 seconds to click
as many moles as you can. The moles appear randomly so be ready! </p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start_button">Start!</button>
</div>
<div id="timer">30 seconds left</div>
<div id="gamespace">
</div>
</div>
</body>
</html>
最佳答案
在 .mole
附加到 #gamespace
并存在于页面之前,您要在 .mole
上添加 click 事件处理程序
,请改用事件委托(delegate)
$('#gamespace').on('click','.mole' ,function () {
counter();
});
关于javascript - Jquery .on() 不调用选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36488950/