我有使用 JQuery 和 AJAX 将产品添加到收藏夹的代码,我的 JavaScript 代码如下所示:
$('.product-item-btn-fav').on('click', function(e){
b = $(this).data("product_number");
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
$(this).addClass("active");
} else {
if (d == -1) {
$(this).removeClass("active");
}
}
}
})
});
和 HTML:
<a class="product-item-btn-fav" data-product_number="[%item.product_number%]">
<svg class="svg-icon-heart-filled">
<use xlink:href="[%domain.url_media%]/images/svg-sprite.svg#svg-icon-heart-filled"></use>
</svg>
</a>
此代码有效,它在后端将产品添加到收藏夹列表中(因此 AJAX 有效并返回有效结果 1 或 -1),但此调用 $(this).addClass("active");
没有将 css 类添加到 <a>
标签。
最佳答案
您必须将 $(this)
存储在 a
的变量中
$('.product-item-btn-fav').on('click', function(e){
b = $(this).data("product_number");
var _t = $(this);
$.ajax({
type: "POST",
url: domain + "/ajax/favorite/" + b,
success: function (a) {
var d = parseInt($(a).find("#result").html());
if (d == 1) {
_t.addClass("active");
} else {
if (d == -1) {
_t.removeClass("active");
}
}
}
})
});
关于javascript - 无法将类添加到单击的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269184/