使用 jQuery 更新按钮上的数据属性

Updating data-attr on a button with jQuery

我试图在成功响应中将 ('.follow') 元素的 data-action 属性更新为 unfollow,但它没有更新。

我做错了什么?

$('.follow').click(function() {
    var id = $(this).data("id");
    var action = $(this).data("action");
    var url = '/action/' + action;
    $.ajax({
        url: url,
        headers: {
            'TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            id: id
        },
        type: "POST",
        success: function(v) {
            if (v.response == "OK") {
                $(this).data('action', 'unfollow');
            }
            if (v.response == "E") {
                alert('there was an error');
            }
        }
    });
});

编辑

添加问题元素是一个按钮这一事实,因为下面提供的解决方案仍然无效。

<button class="follow" data-id="<?php echo $profile->id; ?>" data-action="follow">FOLLOW</button>

第二次编辑

只是想更新这个问题,以防其他人发现自己处于类似情况。

事实证明,Nir Tzezana 接受的答案是绝对正确的。我无法让它工作的原因是 Firefox 有问题。这不是第一次发生这样的事情,但我总是忘记这可能是一个问题。

所以,故事的寓意是.. 如果您正在使用 Firefox 并且您确信您的代码可以正常工作 - 但它似乎无法正常工作 - 退出 Firefox 并重新启动它(特别是如果你已经浏览器打开了很长时间)。很可能您的代码一直在工作。

$(this)指的是return函数。
使用粗箭头函数或此 self 技巧。

$('.follow').click(function () {
   var id = $(this).data("id");
   var action = $(this).data("action");

   // Define self to be the .follow element
   var self = $(this);

   var url = '/action/' + action;

   $.ajax({

       url: url,
       headers: {
             'TOKEN': $('meta[name="csrf-token"]').attr('content')
       },
       data: {
           id: id
       },
       type: "POST",

       success: function(v){

           if (v.response == "OK") {

               self.data('action', 'unfollow');
           }

           if  (v.response == "E") {

               alert('there was an error');
           }
       }
   });

});

this 不引用当前元素,即 $.ajax() 成功处理程序中的 .follow。您可以使用 $.ajax() context option

$('.follow').click(function () {
    $.ajax({
        context: this,
        success: function(){
           //this: it will refer to clicked button
        }
    });
});

并且 <button> 元素的默认操作是 submit,如果按钮被包装在表单中,则使用 type="button"

<button type="button" class="follow" data-id="<?php echo $profile->id; ?>" data-action="follow">FOLLOW</button>