我正在尝试让Jquery删除函数,这是我写的代码-
$("a.delete").click(function(){
var target = $(this).attr("id");
var c = confirm('Do you really want to delete this category?');
if(c==true) {
$(target+"ul").delay(3000).fadeOut(200);
}
else {
return false;
}
});
好了,现在问题来了,当我按下带有class delete的按钮a时,它正确地显示了对话框(id是正确的),但在我按下yes后,它会用php删除它,而没有jquery fadeOut效果。我的php代码-
public function deleteCategory() {
if(isset($_GET['action']) && $_GET['action'] == 'delete') {
$id = (int)$_GET['id'];
$sql = "DELETE FROM `categories` WHERE `id` = '".$id."'";
mysql_query($sql);
}
}
不确定问题出在哪里,但我认为它在$(target+"ul")内,因为我不确定它是否会将目标值和ul相加。
此外,如果我按"否",如何阻止删除?目前,如果我按"否",它仍然会删除该类别。
如果您需要任何其他信息,请询问。
完整代码-
public function showCategories() {
if(isset($_SESSION['logged_in']) && isset($_SESSION['user_level']) && $_SESSION['user_level'] == 'admin') {
$sql = "SELECT * FROM `categories`";
$q = mysql_query($sql);
if(mysql_num_rows($q) > 0) {
?>
<div class="recentorders" style="display: none;" id="categoryBox">
<h5 class="colr">Categories</h5>
<div class="account_table" style="width: 688px;">
<ul class="headtable" style="width: 680px;">
<li class="order">ID</li>
<li class="action" style="width: 430px;">Category Name</li>
<li class="action nobordr">Options</li>
</ul>
<?php
while($row = mysql_fetch_array($q)) {
?>
<ul class="contable" style="width: 680px;" id="cat<?php echo $row['id']; ?>ul">
<li class="order"><?php echo $row['id']; ?></li>
<li class="action" style="width: 430px;"><?php echo $row['name']; ?></li>
<li class="action nobordr"><a href="?action=edit&id=<?php echo $row['id']; ?>#" class="first">Edit</a><a class="delete" id="cat<?php echo $row['id']; ?>" href="?action=delete&id=<?php echo $row['id']; ?>#">Delete</a></li>
</ul>
<?php
}
?>
</div>
</div>
<?php
}
else {
// No categories created, please create one first.
}
}
else {
header('location: account.php');
}
}
public function deleteCategory() {
if(isset($_GET['action']) && $_GET['action'] == 'delete') {
$id = (int)$_GET['id'];
$sql = "DELETE FROM `categories` WHERE `id` = '".$id."'";
mysql_query($sql);
}
}
如果您按ID搜索,则需要在选择器前面加一个"#":
jsFiddle:上的100%工作样本
http://jsfiddle.net/E7QfY/
更改
$(target+"ul").delay(3000).fadeOut(200);
至
$('#' + target+"ul").delay(3000).fadeOut(200);
或
$(this).closest('ul').delay(3000).fadeOut(200);
我还将代码修改为:
$("a.delete").click(function(event){
if(confirm('Do you really want to delete this category?') == true){
$(this).closest('ul').delay(3000).fadeOut(200);
window.location.href = $(this).attr('href'); //OR use AJAX and do an event.preventDefault();
}
else
event.preventDefault();
});
这是因为您使用的锚标记会导致回发到服务器,从而在您看到动画之前刷新页面。请确保您的锚标记有一个定义为"#"的href,以阻止回发。
您应该使用除标记之外的其他东西,例如span或div。然后在单击此元素后进行渐变,并在其重定向到删除对象的PHP脚本后:
$("SPAN,DIV.delete").click(function(){
var target = $(this).attr("id");
var c = confirm('Do you really want to delete this category?');
if(c==true) {
$(target+"ul").delay(3000).fadeOut(200);
window.location.href = URL TO PHP FILE
}
else {
return false;
}
});