根据this answer以及SO上的许多其他文章,我已经看到了在元素具有ID的情况下刷新元素(成功调用之后)的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();
});
发生了什么事
我要实现的目标:
答案 0 :(得分:1)
如果您只想更新所单击的按钮,只需获取对其的引用并在周围的元素上调用更新:
$('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');