Select 只有点击的按钮 JQuery

Select only the clicked button JQuery

我有这个 ajax 功能,它应该改变点击按钮的样式,但由于某种原因它不起作用。我在控制台中没有收到任何错误,并且 ajax 调用成功知道这里出了什么问题吗?

function AcceptOffer(id)
{
    var json = {
        id : id
    };

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AcceptOffer", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function() {
            $(this).text("Accepted");
            $(this).css("background-color", "green");
            $(this).css("color", "white");
            $(this).attr('disabled', true);

        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}
</script> 

Html:

<a href="javascript:void(0)" onclick="AcceptOffer('@item.OfferId')" class="btn btn-default acceptbtn">Accept</a>

您的问题是 this 的使用不当。您使用它的方式,它将引用您传递给 ajax 命令的对象

function AcceptOffer(id)
{
    var json = {
        id : id
    };

    var elemYouWantToChange =...;

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AcceptOffer", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function() {
            $(elemYouWantToChange).text("Accepted");
            $(elemYouWantToChange).css("background-color", "green");
            $(elemYouWantToChange).css("color", "white");
            $(elemYouWantToChange).attr('disabled', true);

        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}

-- 编辑--

在 javascript 中,您会听到这样的点击:

elem.addEventListener('click', function(e) {
  console.log(e.target); // You need to get e.target to AcceptOffer so it can style the correct element
  AcceptOffer(...);
});

在你的代码中 this 没有指向锚标签,你只需要将 this 引用传递给你的函数。

function AcceptOffer(ele, id)
{
var json = {
    id : id
};

$.ajax({
    type: 'POST',
    url: "@Url.Action("AcceptOffer", "Product")",
    dataType : "json",
    data: {"json": JSON.stringify(json)},
    success: function() {
        $(ele).text("Accepted");
        $(ele).css("background-color", "green");
        $(ele).css("color", "white");
        $(ele).attr('disabled', true);

    },
    error: function(data) {
        alert('Some error');
        window.location.reload();
    }
});
}

所以锚标签将是:

<a href="javascript:void(0)" onclick="AcceptOffer(this, '@item.OfferId')" class="btn btn-default acceptbtn">Accept</a>