【发布时间】:2015-01-10 10:50:33
【问题描述】:
我正在为学校作业制作一个用 PHP 做的应用程序。
此时,我可以添加新任务了。但问题是:
- 当我单击一个 div(删除它)时,该 div 被删除,但所有其他任务都变得不可见。如果我创建一个新任务,它们只会再次出现。
这是我的代码
文件Index.php
<div class="container">
<form action="/Periodeopdracht/index.php" method="POST">
<div class="headerToDo">
<input class="addText title" type="text" value="Click to add a task" name="nextToDo">
<input class="clickablePlus" type="submit" value="+" name="submit"></div>
</form>
<?php if(!$empty): ?>
<?php foreach ($_SESSION["todoList"] as $_SESSION["key"] => $toDo): ?>
<div class="toDo">
<form action="/Periodeopdracht/index.php" method="POST">
<button value="<?php echo $_SESSION["key"] ?>" name="delete" class="delete" type="submit" >X</button>
<button value="<?php echo $_SESSION["key"] ?>" name="done" class="done" type="submit" >V</button>
<div value="<?php echo $_SESSION["key"] ?>" class="textToDo"><?= $toDo ?></div>
</form>
</div>
<?php endforeach ?>
<?php endif ?>
</div>
应用程序.php
<?php
session_start();
$GLOBALS["empty"] = true;
$_SESSION['todoList'] = isset($_SESSION['todoList']) ? $_SESSION['todoList'] : array();
if(isset($_POST["submit"]))
{
$empty = false;
array_unshift($_SESSION['todoList'], $_POST["nextToDo"]);
}
if(isset($_POST["delete"]))
{
unset($_SESSION['todoList'][$_SESSION["key"]]);
//var_dump($key);
}
?>
【问题讨论】:
-
foreach ($_SESSION["todoList"] as $_SESSION["key"] => $toDo)那行对我来说看起来很奇怪。每次迭代都为$_SESSION["key"]分配一个新值。在执行结束时,$_SESSION["key"]将包含最后看到的值。这是你想做的吗?你能告诉我们$_SESSION["key"]和$_SESSION["todoList"]应该包含什么吗? -
'$_SESSION["key"]' 是每个 div 的唯一编号,因此我可以找出单击了哪个 div。 '$_SESSION["todoList"]' 应该包含所有添加的任务。