在平时的项目工作中经常会需要在ajax中使用$(this)方法,但是在ajax中直接使用貌似并不起作用,在此介绍一个简单的解决方案:
在ajax前面先将$(this)赋值给一个变量==>然后在ajax里面通过这个变量来操作当前元素

代码:
$(function () {
$(".btn").click(function () {
var friends_username = $(this).nextAll(".username_for_ajax").text();
var btn_add = $(this);
$.ajax({
url:"/blog/add_friends",
type:"POST",
data:{
content:friends_username
},
success:function () {
console.log("成功");
btn_add.hide();
btn_add.nextAll("#friends_off").show();
},
error:function () {
console.log("失败")
}
})
})
网友评论