<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>翻版记忆游戏</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
h3{
margin-left: 40px;
}
table{
margin-left: 20px;
}
td{
width:50px;height:50px;background: yellow;text-align: center;
}
</style>
<
script>
window.onload=function(){
var pai=document.getElementsByTagName("td");
var bushu=document.getElementById("bushu");
var bu=0;
var ceshi=document.getElementById("ceshi");
var fen=document.getElementById("fen");
bian(0,"找");
bian(1,"张");
bian(2,"同");
bian(3,"两");
bian(4,"到");
bian(5,"相");
bian(6,"牌");
bian(7,"的");
bian(8,"两");
bian(9,"同");
bian(10,"牌");
bian(11,"张");
bian(12,"的");
bian(13,"找");
bian(14,"到");
bian(15,"相");
var hy=0;
function bian(j,zi){
var i=0; //当样式变成最初后,i并没有被清楚,所以,被点击后的会出现问题
pai[j].onclick=function(){
i++;bu++;bushu.value=bu;
if(i%2==1){
this.style.backgroundColor="green";
this.innerHTML=zi;
hy++;
}
else{
this.style.backgroundColor="yellow";
this.innerHTML="";
hy--;
}
fhy();
}
}
ceshi.onclick=function(){
alert(hy);
}
function fhy(){
fen.value=hy;
if(hy%3==0){
for(var i=0;i<pai.length;i++){
pai[i].style.backgroundColor="yellow";
pai[i].innerHTML=""; }
}}
}
</script>
</head>
<body>
<h3>找到相同的两张牌</h3>
<table>
<tr>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
</tr>
<tr>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
</tr>
<tr>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
</tr>
<tr>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
</tr>
</table>
<form action="">
<p></p>
用时:<input type="text" /><br>
得分:<input type="text" / id="fen"><br>
步数:<input type="text" id="bushu" value="0"; />
<button id="ceshi">测试</button>
</form>
</body>
</html>
如上面的代码,遇到一个问题:当我点击第三个绿色的元素的时候,全部背景变回最初状态。
但是,另一个函数里的i值并没有还原。
点击过的元素再次点击的话,就会出现问题了,怎样解决?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
试了一下,没仔细看你的代码,先清理一下思路:
pair[0]
pair[1]
,然后进行下面的逻辑> 1. 如果两张相同(
pair[0] === pair[1]
),保持状态,重置 pair:pair = []
; 检查是否完全翻转> 2. 如果两张不同,设置个延时都翻回去
setTimeout(function() { turnBack(pair) }, 1000);
,再重置 pair:pair = []
;顺便说一下,代码如果放下面,可以不用
onload