jQuery getting wrong value when getting data attribute
P粉052724364
P粉052724364 2023-11-01 23:01:19
0
1
594

I have a div with data attributes

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粉052724364
P粉052724364

reply all (1)
P粉183077097

The first time.data()is used to access thedata-*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.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!