我对编程很陌生,所以最好能得到一些帮助。
为什么按下按钮时变量不会更新?
HTML:
<h1>NIM</h1>
<p>Welcome to a simple edition of the game NIM</p>
<table>
<tr>
<th>You</th>
<th>Left</th>
<th>PC</th>
</tr>
<tr>
<td><p id="pl" class="nr">0</p></td>
<td><p id="a" class="nr">25</p></td>
<td><p id="pc" class="nr">0</p></td>
</tr>
</table>
<br>
<p>How many do you want to pull?</p>
<input type="number" id="val" value="1" min="1" max="3">
<button id="turn">Trekk</button>
JavaScript的:
$('#turn').click(function () {
var val = parseInt($('#val').val()),
player = parseInt($('#pl').html()),
pc = parseInt($('#pc').html()),
total = parseInt($('#a').html());
console.log(val);
console.log(total);
do {
switch (val) {
case 1:
total -= 4;
player += 1;
pc += 3;
break;
case 'b2':
total -= 4;
player += 2;
pc += 2;
break;
case 'b3':
total -= 4;
player += 3;
pc += 1;
break;
}
} while (total > 1);});
我可能对c ++更熟悉,这是我第一次在javascript / jquery中尝试do循环。
答案 0 :(得分:1)
我认为这是你想要制作的游戏。好好享受!
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var val = 0; //Initial value of the input box
var player = parseInt($('#pl').html()); //Player score
var pc = parseInt($('#pc').html()); //pc score
var total = parseInt($('#a').html()); //Total left
$('#turn').click(function () {
val = parseInt($('#val').val());
console.log(val);
console.log(total);
if(total > 0){
switch (val) {
case 1:
total -= 4;
player += 1;
pc += 3;
break;
case 2:
total -= 4;
player += 2;
pc += 2;
break;
case 3:
total -= 4;
player += 3;
pc += 1;
break;
}
$('#pl').html(player);
$('#pc').html(pc);
$('#a').html(total);
}
});
});
</script>
</head>
<body>
<h1>NIM</h1>
<p>Welcome to a simple edition of the game NIM</p>
<table>
<tr>
<th>You</th>
<th>Left</th>
<th>PC</th>
</tr>
<tr>
<td><p id="pl">0</p></td>
<td><p id="a">25</p></td>
<td><p id="pc">0</p></td>
</tr>
</table>
<br>
<p>How many do you want to pull?</p>
<input type="number" id="val" value="1" min="1" max="3">
<button id="turn">Trekk</button>
</body>
</html>
<强>小提琴强>
https://jsfiddle.net/1o6qxw9c/
你的错误
JavaScript不同于C&#39;。恭喜您使用Web语言,因为JS在客户端和服务器端都使用。努力学习,先学习简单的基本操作,然后在一年后学习OOJS。虽然,它提供了光荣的功能,但如果不能很好地理解,那么大多数时候你会对弹出的结果感到困惑!