首页 > 解决方案 > 数据属性更新后Jquery获取新值

问题描述

我正在通过 ajax 响应更新链接属性值。但是当我再次单击按钮/链接时,获取的是旧值而不是新值。

以下是我的代码;

HTML

<div class="calendar-control"><a class="evecal-month-view-control fright next-month" href="#" data-month="2" data-year="2019">Next</a><span class="text-center month-name">January 2019</span><a class="evecal-month-view-control fright prev-month" href="#" data-month="12" data-year="2018">Previous</a></div>

和 Jquery 代码。

jQuery(document).on('click', '.evecal-month-view-control', function(e){
    e.preventDefault();
    var month = jQuery(this).data('month');
    var year = jQuery(this).data('year');
    console.log(month);
    _getMonthCalendar(month, year);
});

var _getMonthCalendar = function(m, y){
    jQuery.ajax({
        type: 'POST',
        url: eventcaldata.ajaxurl,
        data: {
            action: 'ec_ajax_month_table',
            year: y,
            month: m,
            nonce: eventcaldata.nonce,
        },
        beforeSend: function(){
            console.log('sending...');
        },
        success: function(response){
            jQuery('.next-month').attr( 'data-month', response.nextmonth.month );
            jQuery('.next-month').attr( 'data-year', response.nextmonth.year );
            jQuery('.prev-month').attr( 'data-month', response.prevmonth.month);
            jQuery('.prev-month').attr( 'data-year', response.prevmonth.year);
        }
    });
}

首先在.next-month课堂上,data-month属性值2 然后3在响应后更改为。但是当我再次单击该按钮时,我得到2了应该得到的值3

标签: javascriptjquery

解决方案


jQuery 对象上的 .data() 方法缓存初始读取的值。随后对 .data() 的调用将首先查看 jQuery 的数据存储并向您发送该值。.attr() 不会更新数据存储,但会更新 HTML 中的属性。使用 .data() 或 .attr() 但避免混搭。


推荐阅读