jQuery dynamic img 在 Ajax 请求后更改



HTML

 <a href="#" rel="39" title="Favorit entfernen?" class="add_favorit">
<img src="/maxyourhealth/assets/images/icon/bookmark_active.svg" alt="Dein Favorit" data-alt-src="/maxyourhealth/assets/images/icon/bookmark.svg" width="19" height="27">
</a>

jQuery

 $('.add_favorit').click(function(e) {
    e.preventDefault();
    var aid = $(this).attr("rel");
    var img_src = $(this).children("img").attr("src");
    var img_new = $(this).children("img").attr("data-alt-src");
        $.ajax({
                type: "POST",
                url: "/maxyourhealth/assets/ajax/inc.favorit.php",
                data: {a1:aid},
                success: function(data) {
                alert(data);
                  $(this).children("img").attr("src", img_new);
                  $(this).children("img").attr("data-alt-src", img_el);
                } 
                })
})

这是一个脚本,用于添加一些文章作为个人收藏夹。我试图在 ajax 调用后更改img,但更改不起作用。

知道为什么吗?

在 ajax 方法的成功处理程序中,this 的值与调用它时的值不同。 为了使它成为相同的值,有几种方法可以做到这一点。

1(将this保存到变量中

var that = this;
$.ajax({
    ...
    , success: function(){
        //use 'that' in here instead of this
    }
});

2( 使用 ajax 方法上的context选项。 参考 api.jquery.com/jQuery.ajax

$.ajax({
    ...
    , context: this
    , success: function(){
        //'this' will be the same inside the ajax as it was outside
    }
});

3( 使用箭头功能(ES6 功能(

$.ajax({
    ...
    , success: () => {
        //use 'this', as arrow methods do not change the value of this
    }
});

这是一个常见的问题,其中this(或$(this)(的上下文被更改。

在这种情况下,您可以做的是使用 ES6 箭头函数来解决此问题。

改变

success: function(data) {
    alert(data);
    $(this).children("img").attr("src", img_new);
    $(this).children("img").attr("data-alt-src", img_el);
} 

// the parenthesis around 'data' can be stripped off if there is only one parameter.
success: (data) => {
    alert(data);
    $(this).children("img").attr("src", img_new);
    $(this).children("img").attr("data-alt-src", img_el);
}

您也可以使用context: this但是,我尝试提倡箭头函数纯粹是因为代码变得更加清晰,并且由于不必定义另一个引用$(this)的变量,它可以使您免于"代码异味"。

阅读材料和兼容性

我可以使用吗

ES6新功能,词汇this

最新更新