Home  >  Q&A  >  body text

jQuery getting wrong value when getting data attribute

I have a div with data attributes

<div class='p1' data-location='1'></div>

I have a script like this

$('button').click(function(){

    var loc = $('.p1').data('location');
    alert('data location is'+loc);//SHOW THE DATA

    var num = 10;
    var count = loc;
    var element = $('.p1');
    var intv = setInterval(anim,1000); 
    function anim(){
        count++;
        num--;
        if(count==37){count = 1;}
        if(num==1){clearInterval(intv);}
        $(element).animateCSS('bounceOut',{
            callback: function(){
                $(element).attr('data-location',count);
                $(element).animateCSS('bounceIn');
            }
        });

    }
    anim();

});

With the above script, the data position property will be updated to 10, but if I click the button again, the data position is still 1

P粉052724364P粉052724364246 days ago414

reply all(1)I'll reply

  • P粉183077097

    P粉1830770972023-11-02 15:33:37

    The first time .data() is used to access the data-* property, the value of the property is cached internally by jQuery, and .data() Use caching from then on. Updating an attribute using .attr() will not update the cache, you need to use .data() to update it. That's why you need to use

    $(element).data('location', count);

    Update it.

    Reply
    0
  • CancelReply