使用jQuery更新按钮上的data-attr

时间:2018-03-26 11:56:36

标签: javascript jquery ajax jquery-selectors

我正在尝试在成功回复中将data-action元素的('.follow')属性更新为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并重新启动它(特别是如果你有浏览器打开很长时间)。有可能你的代码一直在工作。

2 个答案:

答案 0 :(得分:2)

$(this)指的是返回功能 使用胖箭头功能或此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');
           }
       }
   });

});

答案 1 :(得分:1)

this deos not引用当前元素,即.follow成功处理程序中的$.ajax()。您可以使用$.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>