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

标签 javascript jquery ajax jquery-selectors

我正在尝试将 ('.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) 指的是返回函数。
使用粗箭头函数或此 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');
           }
       }
   });

});

关于javascript - 使用 jQuery 更新按钮上的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490895/

相关文章:

javascript - 将 eventListener 添加到复选框

jquery - 将背景图像与背景渐变相结合

jQuery :not() issue

javascript - 使用 javascript 和 jquery 动态调整 div 的大小?

javascript - Uncaught ReferenceError : url is not defined

javascript - 延迟回调直到脚本被添加到文档?

javascript - 从 gulp typescript js 流中分割 src 和测试文件

jquery - AJAX - 如何从我的静态 [webmethod] 检索返回值

php - 如何使用 PHP 和 Ajax 将表单数据插入 MySQL 数据库表中?

javascript - 将 javascript 放入 jquery .html 函数