gpt4 book ai didi

javascript - onclick事件不改变元素ID

转载 作者:行者123 更新时间:2023-11-28 02:24:10 24 4
gpt4 key购买 nike

我正在尝试在浏览器中编写幻灯片拼图。当用户单击网格上与 BLANK 方 block 相邻的方 block 时,单击的方 block 应与 BLANK 交换。

编辑:这是它完成后应该做的:https://en.wikipedia.org/wiki/15_puzzle

我试图通过使用 onclick 触发器调用 JavaScript 函数来实现此目的,该函数首先检查方 block 是否为有效移动,然后切换方 block 的 ID 属性。我的 CSS 文件包含每个方 block 的图像,链接到方 block 的 ID。

就目前而言,点击方 block 时不会执行任何操作。

<html>

<head>
<link rel="stylesheet" type="text/css" href="Puzzle.css">
<title>Fifteen Puzzle</title>
<script type="text/javascript" src="Puzzle.js" defer="defer"></script>
</head>

<body onload="startPuzzle()">
<div class="container">
<div class="square" id="square0" onclick="A.slide(0, 0, this.id)"> </div>
<div class="square" id="square1" onclick="A.slide(1, 0, this.id)"> </div>
<div class="square" id="square2" onclick="A.slide(2, 0, this.id)"> </div>
/* And so on to the 16th square: */
<div class="square" id="squareBLANK" onclick="A.slide(3, 3, this.id)"> </div>
</div>
</body>
</html>

JavaScript 文件:

class Puzzle {
constructor () {
this.board = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, "_"]];
}

slide (i, j, a){
x = this.board[i][j];
if (this.board[i+1][j] == "_") {
this.board[i+1][j] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
else if (this.board[i][j+1] == "_") {
this.board[i][j+1] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
else if (this.board[i][j-1] == "_") {
this.board[i][j-1] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
else if (this.board[i-1][j] == "_") {
this.board[i-1][j] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
}


}

function startPuzzle() {let A = new Puzzle();}

那么,谁能说出是什么阻止了方 block 的移动?

最佳答案

您已经创建了一个包含4 个对象board Array

this.board = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, "_"]];

然后你设置你的squareBLANK slide method参数3LastObject, 3Third Value, this.idsquareBLANK .

<div class="square" id="squareBLANK" onclick="A.slide(3, 3, this.id)">  </div>

在您的 Javascript 中,您正在检查 [i]LastObject 表示 [3+1] = 4。您实际上检查了 board Array 中的 5th Object 中的 3rd value,它不存在并且返回 Uncaught TypeError: Cannot read property控制台中未定义的“3”

if (this.board[i+1][j] == "_")

关于javascript - onclick事件不改变元素ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com