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脚本正在执行并且其他所有功能都在工作,但活动类既没有添加也没有删除。

gareth1987 回答:Ajax调用后,Javascript addClass或removeClass在子类中不起作用

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
,

使用:

$(".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");

问候!

本文链接:https://www.f2er.com/3165639.html

大家都在问