简体   繁体   English

jQuery在数据属性更新后获取新值

[英]Jquery getting new value after data attribute update

I am updating link attribute values via ajax response.but When i am again clicking the button/link getting old values instead of new value. 我通过ajax response.update更新链接属性值,但是当我再次单击按钮/链接时,获取旧值而不是新值。

Below is my codes; 下面是我的代码;

HTML 的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>

And Jquery code. 和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);
        }
    });
}

First on .next-month class the data-month attribute value is 2 then it is changed to 3 after response.But When i am again clicking that button i am getting 2 value when it should be 3 首先在.next-month类上, data-month属性值为2然后在响应后将其更改为3当我再次单击该按钮时,我应该获得2值,而应为3

Do not intermix this usage of attr() and data() . 不要混合使用attr()data() data() caches the value that it reads from the element, and does not update the attribute. data()缓存从元素读取的值,并且不更新属性。 So if you update with data, attr will not see it. 因此,如果您使用数据更新,attr将不会看到它。 Pick one or the other, and stick with it. 选择一个或另一个,并坚持下去。

The .data() method on jQuery objects caches the value from the initial read. jQuery对象上的.data()方法缓存初始读取的值。 Subsequent call to .data() will first look in jQuery's data storage and send you that value. 随后对.data()的调用将首先在jQuery的数据存储中查找并向您发送该值。 .attr() won't update the data storage, but will update the attribute in HTML. .attr()不会更新数据存储,但是会更新HTML中的属性。 Use either .data() or .attr() but avoid mix and match. 使用.data()或.attr(),但要避免混合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM