在 ajax 成功函数中获取错误.getsaves.text 不是一个函数

Getting error in ajax success function. getsaves.text is not a function

本文关键字:函数 一个 getsaves 成功 ajax 获取 取错误 text      更新时间:2023-09-26

这是我的代码

<script>jQuery('.appendurl').click(function(e){
                e.preventDefault();
                var getsaves = jQuery(this).text();
                var ajaxurl = '/wp-admin/admin-ajax.php';
                jQuery.post(
                    ajaxurl, 
                    {
                        'action': 'add_to_wishlist',
                        'add_to_wishlist': jQuery(this).attr('data-product-id'),   
                        'product_type': jQuery(this).attr('data-product-type')
                    }, 
                    function(response){
                        if(response.result = 'true'){
                            jQuery(this).closest('.yith-wcwl-add-button').removeClass('show');
                            jQuery(this).closest('.yith-wcwl-add-button').addClass('hide');
                            jQuery(this).closest('.yith-wcwl-wishlistexistsbrowse').removeClass('hide');
                            jQuery(this).closest('.yith-wcwl-wishlistexistsbrowse').addClass('show');
                            saves = getsaves.replace(' saves','');
                            countInc = parseInt(saves, 10) + 1;
                            updatedText = countInc + ' saves';
                            alert(updatedText);
                            getsaves.text(updatedText);
                        }
                    }
                );
            });</script>

我在 ajax 成功函数的最后一行收到错误。 error 是 TypeError: getsaves.text 不是函数 getsaves.text(updateText);

getsaves.text(updatedText)

在警报中,我正在获取值,并且我在该行上方使用的相同 getsave 来替换一些字符串。

getsaves是一个

字符串,而不是一个jQuery对象,所以你不能对它调用.text

我建议你分配$this = jQuery($this)并将后者的所有出现替换为 $this ,然后在有问题的行上使用它。

这也将解决this这些回调中不是您认为的this的问题:

jQuery('.appendurl').click(function(e) {
    e.preventDefault();
    var $this = jQuery(this);
    var getsaves = $this.text();
    var ajaxurl = '/wp-admin/admin-ajax.php';
    jQuery.post(ajaxurl, {
       'action': 'add_to_wishlist',
       'add_to_wishlist': $this.attr('data-product-id'),
       'product_type': $this.attr('data-product-type')
    }, function(response) {
       if (response.result == 'true' ) {  // fixed '=' error here!
           $this.closest('.yith-wcwl-add-button').removeClass('show');
           $this.closest('.yith-wcwl-add-button').addClass('hide');
           $this.closest('.yith-wcwl-wishlistexistsbrowse').removeClass('hide');
           $this.closest('.yith-wcwl-wishlistexistsbrowse').addClass('show');
           saves = getsaves.replace(' saves','');
           countInc = parseInt(saves, 10) + 1;
           updatedText = countInc + ' saves';
           // alert(updatedText);
           $this.text(updatedText);
       }
   });
});

您还可以链接两对.removeClass.addClass调用,例如:

$this.closest('.yith-wcwl-add-button').removeClass('show').addClass('hide');