我正在为一个游戏编写一些代码,以更好地学习 JS,但我遇到了一个问题。我正在使用 jQuery 库来执行动画。
我正在尝试做的事情(参见 //Fade out text 注释):
当玩家按下空格键时,我想隐藏 3 个<p>
具有唯一 ID 的标签。我目前拥有的代码(有点)但问题是我必须按一次空格键,<p>
而我想按一下我想删除的每个标签。如果我使用 text() 方法,那么我只需要按一次空格键即可删除<p>
标签中的所有文本。
这是我的代码:
$(document).ready(function() {
$("body").keypress(
function(event) {
if (event.which == 32) {
if (operator === "+") {
result = parseInt(firstTerm) + parseInt(secondTerm);
}
else if (operator === "-") {
result = parseInt(firstTerm) - parseInt(secondTerm);
}
//reset the player's current expression
firstTerm = "";
operator = "";
secondTerm = "";
//Fade out the text
$("p#term1, p#operator, p#term2 ").fadeToggle("slow");
//$("p#term1, p#operator, p#term2 ").text("");
//clear the board of any selections
for (var i = 0; i < tilesSelected.length; i++) {
$("div#" + tilesSelected[i]).removeClass("tileselected");
}
//check to see if the player has scored a point
if (result === goalNum) {
alert("You just scored 1 point!");
score++;
goalNum = randNumXtoY(1, 30);
$("div#targetnum").text(goalNum);
}
alert(result);
}
});
});
html代码在这里:
<body>
<h1>This is my game. Yay!</h1>
<div id="container">
<div id="currentnum" class="currentstatus">
<p id="term1" class="x"></p>
<p id="operator" class="x"></p>
<p id="term2" class="x"></p>
</div>
<div id="targetnum" class="currentstatus">
<script type="text/javascript">
document.write("<p>" + goalNum +"</p>")
</script>
</div>
</div>
</body>