无法为点击元素添加类:jQuery+AJAX商品收藏功能异常
问题分析与解决方案
你的问题核心是AJAX回调函数里的this指向已经不是触发点击的那个.product-item-btn-fav元素了。默认情况下,jQuery的$.ajax()成功回调里的this指向的是AJAX请求的配置对象,而不是原来的DOM元素,所以调用$(this).addClass("active")自然不会生效。
下面给你几个可行的解决办法:
方法1:提前保存this到变量(最常用且兼容性好)
在点击事件里先把当前元素的引用存到一个变量里,比如$btn,然后在回调里用这个变量操作:
$('.product-item-btn-fav').on('click', function(e){ // 保存当前按钮的引用 const $btn = $(this); const productNumber = $btn.data("product_number"); $.ajax({ type: "POST", url: domain + "/ajax/favorite/" + productNumber, success: function (response) { const result = parseInt($(response).find("#result").html()); if (result === 1) { $btn.addClass("active"); } else if (result === -1) { $btn.removeClass("active"); } } }); });
方法2:使用箭头函数(ES6+语法)
箭头函数不会绑定自己的this,它会继承外层作用域的this,所以在回调里用箭头函数的话,this就还是原来的按钮元素:
$('.product-item-btn-fav').on('click', function(e){ const productNumber = $(this).data("product_number"); $.ajax({ type: "POST", url: domain + "/ajax/favorite/" + productNumber, success: (response) => { const result = parseInt($(response).find("#result").html()); if (result === 1) { $(this).addClass("active"); } else if (result === -1) { $(this).removeClass("active"); } } }); });
注意:如果你的项目需要兼容IE等旧浏览器,这个方法可能不适用,因为IE不支持箭头函数。
方法3:设置AJAX的context选项
jQuery的$.ajax()允许通过context选项指定回调函数里的this指向,把它设置为当前元素即可:
$('.product-item-btn-fav').on('click', function(e){ const productNumber = $(this).data("product_number"); $.ajax({ type: "POST", url: domain + "/ajax/favorite/" + productNumber, context: this, // 指定回调里的this指向当前按钮 success: function (response) { const result = parseInt($(response).find("#result").html()); if (result === 1) { $(this).addClass("active"); } else if (result === -1) { $(this).removeClass("active"); } } }); });
另外,调试时可以在回调里用console.log(this)打印一下,就能直观看到this的指向变化,这也是排查这类问题的常用小技巧哦。
内容的提问来源于stack exchange,提问作者tomsk
相关产品推荐
相关产品推荐

