繁体   English   中英

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

[英]Javascript addClass or removeClass not working in subclass after ajax call

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

我尝试使用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 脚本正在执行并且其他一切正常,但活动的 class 既没有添加也没有删除。

你ajax成功function中的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");

问候!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM