Skip to main content
 首页 » 编程设计

jquery之ajax回调后更改内部文本不起作用

2026年05月17日54mate10pro

我在页面上有十个类似的按钮,它们是我通过页面上的 foreach 循环创建的。

我在使用 jQuery 更改内部文本时遇到问题。

让我用我的元素来解释

     <a class="pr-endorse" id="<%=product.ConfectionaryProductId %>"> 
        <i class="pr-add"></i> 
        <span>+</span> 
        <span class="pr-likes"><%=product.EndorsementCount %></span> 
    </a> 

这是我喜欢的按钮元素之一。

这是提交用户的 Ajax 函数

      $(document).ready(function () { 
        $(".pr-endorse").click(function () { 
            debugger; 
            var productId = $(this).attr("id"); 
            var confId = $("#ConfectioneryId").val(); 
            var countNumber = $(this).find(".pr-likes").html(); 
            $.ajax({ 
                url: '<%: Url.Action("Endorsement","Confectionery")%>', 
                data: { productId: productId, itemId: confId }, 
                type: "POST", 
                async: true, 
                cache: false, 
                success: function (result) { 
 
                    debugger; 
                    $(this).find(".pr-likes").text(result.endoresCount); 
                    alert(result.endoresCount); 
 
                }, 
                error: function (xhr) { 
                    alert(xhr); 
                } 

我认为这部分代码应该解决

  $(this).find(".pr-likes").text(result.endoresCount); 

但是它不起作用?

请您参考如下方法:

我会尝试一下,它应该看起来像这样

$(document).ready(function () { 
    $(".pr-endorse").click(function () { 
 
        var self        = this 
        var productId   = self.id; 
        var confId      = $("#ConfectioneryId").val(); 
        var countNumber = $(this).find(".pr-likes").html(); 
 
        $.ajax({ 
            type : "POST", 
            url  : '<%: Url.Action("Endorsement","Confectionery")%>', 
            data : { 
                productId : productId, 
                itemId    : confId 
            }, 
            dataType : 'json', 
            success : function (result) { 
 
                $(self).find(".pr-likes").text(result.endoresCount); 
                alert(result.endoresCount); 
 
            }, 
            error : function (xhr) { 
                alert(xhr); 
            } 
        }); 
    }); 
}); 

请注意,成功函数中的 this 不是被单击的元素,要返回一个对象,您通常需要设置 dataType,即使 jQuery 会在 header 为正确。