ajax调用后,Javascript addClass或removeClass在子类中不起作用



我有一个ajax脚本,如果不在数据库中,它会插入一个值,如果已经存在,它会删除该值,并根据它在现有按钮中添加或删除类的返回值相应地返回1或0。

我已经尝试使用find()获取子类值,但它仍然不起作用。

<form method="post" class="wish" action="process.php">
<input type='hidden' id='value' name='value' value='1'>
<button type="submit" class="card-fox list active" >fan</button>
</form>

这一行是活动的,如果它不在那里,我希望添加它,如果它在那里,则删除它。

下面是ajax:

$(document).ready(function (e) {
$(".wish").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
if (data == 1) {
$(".list", this).addClass("active");
}
if (data == 2) {
$(".list", this).removeClass("active");
}
},
error: function (e) {}
});
}));
});

问题是,尽管ajax脚本正在执行,其他一切都在工作,但活动类既没有添加也没有删除。

使用:

$(".wish").find('button').addClass("active");
$(".wish").find('button').removeClass("active");

或者:

//when form is submit, make a copy of this
let self = this;
//send ajax
//in success ajax
$(self).find('button').addClass("active");

问候!

ajax成功函数中的this不是表单。
您可以将ajax调用的上下文设置为for来解决此问题。

$.ajax({
context: this, //<- this this is the form, and tells jQuery to set the this of its callbacks to the form

最新更新