简体   繁体   English

为什么removeClass()和addClass()不起作用?

[英]Why won't removeClass() and addClass() work?

I have an AJAX call that will execute successfully, but when it reaches the done() section, it will print out my message "SUCCESS" but not change the classes of the button. 我有一个AJAX调用将成功执行,但是当它到达done()部分时,它将打印出我的消息“ SUCCESS”,但不会更改按钮的类。

$(".btn").click(function () {
    $.ajax({
        method: "POST",
        url: $(this).data("action"),
        data: {
            aId: $(this).data("a-id"),
            bId: $(this).data("b-id"),
            cId: $(this).data("c-id")
        }
    })
    .done(function () {
        console.log("SUCCESS");
        $(this).removeClass("btn-default");
        $(this).addClass("btn-success");
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        alert("FAILURE");
        $(this).removeClass("btn-default").addClass("btn-danger");
    });
});

My guess is that it has to do with that fact that I'm not giving the function a ID of the button to act on, but to act on anything that is clicked that has the class "btn." 我的猜测是,这与以下事实有关:我没有给函数提供要操作的按钮的ID,而是要对具有“ btn”类的任何单击的对象进行操作。 The page this originates from has a long list of buttons which is why they don't have IDs since the page would give them all the same ID. 该页面源自一长串按钮,这就是为什么它们没有ID的原因,因为该页面会赋予它们全部相同的ID。 I suppose I could append a number to the ID, but I would prefer not to do it that way. 我想我可以在ID后面附加一个数字,但是我不希望那样做。 It also doesn't explain why $(this) works in the rest of my AJAX function when retrieving values. 它也没有解释为什么在获取值时$(this)在我的其余AJAX函数中起作用。

$(this) isn't the right this . $(this)是不正确的this Try caching the element. 尝试缓存元素。

$(".btn").click(function () {
    var $btn = $(this);

    $.ajax({
        method: "POST",
        url: $(this).data("action"),
        data: {
            aId: $(this).data("a-id"),
            bId: $(this).data("b-id"),
            cId: $(this).data("c-id")
        }
    })
    .done(function () {
        console.log("SUCCESS");
        $btn.removeClass("btn-default");
        $btn.addClass("btn-success");
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        alert("FAILURE");
        $btn.removeClass("btn-default").addClass("btn-danger");
    });
});

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

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