简体   繁体   English

传递给 javascript 的参数不正确

[英]Incorrect argument being passed to javascript

I am building a simple website for my family to track the jigsaw puzzles they own.我正在为我的家人建立一个简单的网站来跟踪他们拥有的拼图游戏。 One feature is the ability to delete a puzzle they no longer own.一个功能是能够删除他们不再拥有的谜题。 I intend to pass the row ID to a separate file as an argument, but thought I should put a javascript confirmation popup in the middle.我打算将行 ID 作为参数传递给单独的文件,但我认为我应该在中间放置一个 javascript 确认弹出窗口。 I seem to have everything running almost correctly, but the argument being passed is incorrect and I don't know why.我似乎一切都运行得几乎正确,但是传递的参数不正确,我不知道为什么。 It is passing the ID of the last row in the table, rather than the current row ID.它传递的是表中最后一行的 ID,而不是当前行 ID。 Hoping someone can point me in the right direction.希望有人能指出我正确的方向。

PHP Code PHP 代码

while ($row = $result->fetch_assoc()) {
  echo "<script>var puzzleID = " . $row['id'] . "</script>";
  echo "<td><a href='puzzleedit.php?=" . $row['id'] . "'>Edit</a> | <button onclick='confirmationBox()'>Delete</button></td>";
}

JS Code in a separate file JS 代码在一个单独的文件中

function confirmationBox() {
    if (confirm("Are you sure you want to delete this puzzle?")) {
        window.location = './puzzledelete.php?=' + puzzleID
    } else {
    }
}

The interesting thing is that using $row['id'] in the edit link works as expected, it is grabbing the correct row ID from the database.有趣的是,在编辑链接中使用$row['id']可以按预期工作,它从数据库中获取正确的行 ID。 The $row['id'] in the script is grabbing the table's last row ID.脚本中的$row['id']正在获取表的最后一行 ID。

Your loop keeps reassigning puzzleId .您的循环不断重新分配puzzleId When you call confirmationBox() , it will have the last value that was assigned, not the one that was assigned before each <td> .当您调用confirmationBox()时,它将具有分配的最后一个值,而不是在每个<td>之前分配的值。

Instead of using a global variable, use a function parameter.不要使用全局变量,而是使用 function 参数。

while ($row = $result->fetch_assoc()) {
  echo "<td><a href='puzzleedit.php?=" . $row['id'] . "'>Edit</a> | <button onclick='confirmationBox(" . $row['id'] . ")'>Delete</button></td>";
}
function confirmationBox(puzzleID) {
    if (confirm("Are you sure you want to delete this puzzle?")) {
        window.location = './puzzledelete.php?=' + puzzleID
    } else {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM