Обновить стиль кнопки после вызова Ajax - с идентичными классами CSS - PullRequest
2 голосов
/ 10 марта 2019

Согласно этому ответу и многим другим на SO, я видел способы обновления содержимого Ajax (после успешного вызова) на элементе, если у него есть идентификатор.Тем не менее, мне нужно получить это поведение на занятиях.Я пробовал варианты использования $ .each, foreach, this и т. Д., Но все они дают похожие (неправильные) результаты.Может ли кто-нибудь научить меня, как обновлять содержимое только для текущего выбранного элемента?

Вот как я это делаю, но после нажатия кнопки отчета появляются еще 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>
//javascript:
$('body').on('click', '.report-btn', function (e) {
    var id = $(this).data('id');
    var uid = $(this).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)
                $(".refresh-report-after-ajax").load(window.location + " .refresh-report-after-ajax"); 
            }
        });
        e.preventDefault();
    });

Что происходит:

enter image description here

Чего я пытаюсь достичь:

enter image description here

1 Ответ

1 голос
/ 10 марта 2019

Если вы хотите обновить только нажатую кнопку, просто получите ссылку на нее и вызовите обновление для окружающего элемента:

$('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();
});

UPDATE

Вместо вызова .load(…) вы можете напрямую вносить изменения в JavaScript, поскольку вы знаете, каким должен быть результат:

$button.toggleClass('fa-flag-o fa-flag').attr('title', $button.hasClass('fa-flag') ? 'You reported this item.' : 'Report this item');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...