weixin_33727510 2016-09-15 09:01 采纳率: 0%
浏览 30

$ .ajax之后更新类数组

I have a set of buttons in a list, some of them have a disabled class.

What I want to do

When I click a non-disabled button I want to add disabled to ALL the buttons. After finishing the ajax request, I want to have only the previously AND the clicked button to have a disabled class.

I tried

$(document).on('click', '.myButton', function (e) {

    /* Get this Button */
    var $btn = $(this);

    /* Get all disabled Buttons */
    var allDisabled = $('.disabled');

    /* Add disabled to all buttons */
    $('.buttonAction').addClass('disabled');

    /* Do Ajax Stuff */
    $.ajax({
       type: 'GET',
       ...
       success: function (data) {

           /* Remove all 'disabled' from Buttons */
           $('.buttonAction').removeClass('disabled');

           /* Add 'disabled' to this Button */
           $btn.addClass('disabled');

          /* Add 'disabled' to all previous Buttons */
          allDisabled.each(function(){
              $(this).addClass('disabled');
          });       
       },
       ...

   });
});

Unfortunately the allDisabled.each function assigns the disabled to ALL buttons.

WHere am I wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33736048 2016-09-15 09:07
    关注

    Instead of removing and adding a class to all objects, you can only manipulate with those buttons which need to be temporarily disabled:

    $(document).on("click", ".my-button", function() {
        var $btn = $(this);
        var $disableDuringAjax = $(".buttonAction:not(.disabled)").addClass("disabled");
    
        $.ajax({
            type: 'GET'
        })
        .done(function (data) {
           $disableDuringAjax.removeClass("disabled");
           $btn.addClass('disabled');
        });
    });
    

    That way, disabled class will not be toggled twice for buttons, which should not be enabled at all.

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮