美文网首页
1.$(this)在ajax中的使用(示例)

1.$(this)在ajax中的使用(示例)

作者: 零_WYF | 来源:发表于2018-02-03 11:25 被阅读35次

在平时的项目工作中经常会需要在ajax中使用$(this)方法,但是在ajax中直接使用貌似并不起作用,在此介绍一个简单的解决方案:

在ajax前面先将$(this)赋值给一个变量==>然后在ajax里面通过这个变量来操作当前元素
image.png

代码:

$(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("失败")

                }
            })
        })

相关文章

网友评论

      本文标题:1.$(this)在ajax中的使用(示例)

      本文链接:https://www.haomeiwen.com/subject/xaquzxtx.html