Javascript Ajax调用后刷新按钮样式-使用相同的CSS类

Javascript Ajax调用后刷新按钮样式-使用相同的CSS类,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,根据和许多其他人的观点,我已经看到了在元素上刷新Ajax内容(在成功调用之后)的方法,如果元素有ID的话。但是,我需要在类上获得这种行为。我尝试过使用$的各种变体。each、foreach、this等等,但它们都会产生类似(不正确)的结果。有人能教我如何仅刷新当前单击项目的内容吗 我就是这样做的,但是在单击report按钮之后,又出现了16个按钮,因为它调用了该类的所有按钮 <!--html:--> <!-- If userReported function returns t

根据和许多其他人的观点,我已经看到了在元素上刷新Ajax内容(在成功调用之后)的方法,如果元素有ID的话。但是,我需要在类上获得这种行为。我尝试过使用$的各种变体。each、foreach、this等等,但它们都会产生类似(不正确)的结果。有人能教我如何仅刷新当前单击项目的内容吗

我就是这样做的,但是在单击report按钮之后,又出现了16个按钮,因为它调用了该类的所有按钮

<!--html:-->
<!-- If userReported function returns true, then user already reported this item. -->
<!-- This code block runs in a loop of about 10-17 iterations -->
            <span class="report-btn_wrapper refresh-report-after-ajax">
            <i <?php if (userReported($product_ref)) { ?> title="Report this item" class="fa fa-flag-o report-btn" <?php } else { ?> title="You reported this item" class="fa fa-flag report-btn" <?php } ?> data-id="<?=$product_ref;?>" data-uid="<?=$user_ref;?>"></i>
            </span>
正在发生的事情:

我正在努力实现的目标:


如果您只想更新单击的按钮,只需获取对它的引用并调用周围元素的更新:

$('body').on('click', '.report-btn', function (e) {
    var $button = $(this);
    var id = $button.data('id');
    var uid = $button.data('uid');
    $.ajax({
        type: 'POST',
        url: 'report.inc.php',
        data: {
          product_ref : id,
          user_ref : uid
        },
        success: function (html) {
            //give user a notification message
            notification(html, 0);
            //refresh the button (if user clicked, button is red, if user did not click, button is grey)
            $button.closest(".refresh-report-after-ajax").load(window.location + " .refresh-report-after-ajax"); 
        }
    });
    e.preventDefault();
});
更新

您可以直接在JavaScript中执行更改,而不是
.load(…)
调用,因为您知道结果应该是什么:

$button.toggleClass('fa-flag-o fa-flag').attr('title', $button.hasClass('fa-flag') ? 'You reported this item.' : 'Report this item');

var$this=$(this)
添加到
click函数的开头,然后在
success函数
中,使用单击处理程序中的
$this
$this
单击按钮)执行所需操作,但在AJAX调用之前,
this
指的是单击的按钮。使用类似于
var$span=$(this).closest('.some parent class').find('.refresh report after ajax')来存储它。在成功调用中,使用
$span.load(…)
(您还应该检查正在加载的URL,因为我认为您不是想让类成为它的一部分吗?)我尝试了这个逻辑,但失败了,因为类仍然在load()函数中复制。当使用类时,可能有一种完全不同的方法,因为load()函数调用一个类-它不知道调用哪个类,所以它得到了所有。@MehdiDehghani添加了HTML-因为它在一个while循环中,同一页上有大量重复的类。这给出了相同的结果,我以前也尝试过。我想是因为
window.location+“(class)”
正在获取所有的类。我怎么能只挑出当前的类呢?但这一定是PHP代码中的错误逻辑。在我看来,您可能正在一个循环中创建多个按钮。调用
window.location+”。在ajax之后刷新报告“
可能不是您想要做的,正如Chris G已经指出的那样。如何从循环中删除按钮?该页面在数据库中循环,并在它们被回显时对其进行样式设置。我不知道如何将按钮与产品分开。我假设,您的url需要一个额外的参数,以便PHP脚本只呈现您想要更新的标志。尝试添加您的
id
uid
,并扩展php脚本以根据参数(如果存在)进行过滤。另一方面:为什么不直接在JavaScript中更改样式和标题,而不需要额外的回调呢?你知道,结果应该是什么。请看我的更新,它不会执行第二次回调。相反,它切换fa-flag-o和fa-flag类,并相应地切换标题。
$button.toggleClass('fa-flag-o fa-flag').attr('title', $button.hasClass('fa-flag') ? 'You reported this item.' : 'Report this item');