我认为我的beforeSend函数不起作用的原因(没有背景颜色更改)是因为它没有看到变量id的值。如何正确引用从表单发布的id变量。这是相关的html和js:
HTML
<div id="rec<?php echo $id; ?>"class="del_box">
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
JS
$("document").ready(function() {
$(".delform").submit(function() {
data = $(this).serialize();
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$("#" + "rec" + data["id"]).animate({
'backgroundColor': '#fb6c6c'
}, 600);
}
success: function(response) {
if (response.success) {
$("#rec" + response.idc).slideUp(600, function() {
$("#rec" + response.idc).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});
return false;
}
});
});
CSS
.del_box {
background-image: none;
background-color:#9F9F9F;
}
答案 0 :(得分:2)
为什么要将#与rec分开?
$("#" + "rec" + data["id"])
你也可以这样写:
$("#rec" + data["id"])
无论如何Ramsay Smith的答案是对的!
答案 1 :(得分:1)
如果你想做我认为你想做的事情,那么beforeSend
就没有必要了。您正在为一个对象设置动画,但这不一定需要与Ajax请求相关联。只需在请求之外做动画。像这样:
data = $(this).serialize();
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
});
$("#rec" + data["id"]).animate({'backgroundColor': '#fb6c6c'}, 600);
return false;
}