Get invalid value in jquery data attribute

I have a div with data attributes like

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

and I have a script like

 $('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 a script above the data location attribute will be updated to 10, but if I click the button again, the data location will remain 1

+5
source share
3 answers

The first time you use .data() to access the data-* attribute, the value of this attribute is internally cached by jQuery, and .data() uses the cache and then turns it on. Updating an attribute using .attr() does not update the cache, you need to use .data() to update it. That is why you need to use

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

to update it.

+6
source
  $(element).attr('data-location',count); 

differs from

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

so use the second one instead.

Read more about Data vs. Attr .

+2
source

you set the attr property, not the data, using .attr('data-location',count) . to get the attribute you need to use .attr('data-location') :

 var loc = $('.p1').attr('data-location'); 
+1
source

Source: https://habr.com/ru/post/1212673/


All Articles