i have a div with data attribut like
我有一个数据仓库的div
<div class='p1' data-location='1'></div>
and i have 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 the script above the data-location attribute will be updated to 10, but if i click the button again, the data-location is still 1
在上面的脚本中,data-location属性将被更新为10,但是如果我再次单击按钮,数据位置仍然是1
3 个解决方案
#1
6
The first time that you use .data()
to access a data-*
attribute, the value of that attribute is cached internally by jQuery, and .data()
uses the cache from then on. Updating the attribute with .attr()
does not update the cache, you need to use .data()
to update it. That's why you need to use
第一次使用.data()来访问数据-*属性时,jQuery内部会缓存该属性的值,并且.data()从那时起使用缓存。使用.attr()更新属性不会更新缓存,需要使用.data()更新缓存。这就是为什么你需要使用
$(element).data('location', count);
to update it.
更新它。
#2
2
$(element).attr('data-location',count);
is different than
是不同的
$(element).data('location',count);
so, use the second instead.
所以,用第二个代替。
Check Data vs Attr for details.
详细检查数据与Attr。
#3
1
you are setting the attr property and not data using .attr('data-location',count)
. to get the attribute you need to use .attr('data-location')
:
您正在使用.attr(“data-location”,count)设置attr属性,而不是数据。要获取属性,需要使用.attr(“data-location”):
var loc = $('.p1').attr('data-location');
#1
6
The first time that you use .data()
to access a data-*
attribute, the value of that attribute is cached internally by jQuery, and .data()
uses the cache from then on. Updating the attribute with .attr()
does not update the cache, you need to use .data()
to update it. That's why you need to use
第一次使用.data()来访问数据-*属性时,jQuery内部会缓存该属性的值,并且.data()从那时起使用缓存。使用.attr()更新属性不会更新缓存,需要使用.data()更新缓存。这就是为什么你需要使用
$(element).data('location', count);
to update it.
更新它。
#2
2
$(element).attr('data-location',count);
is different than
是不同的
$(element).data('location',count);
so, use the second instead.
所以,用第二个代替。
Check Data vs Attr for details.
详细检查数据与Attr。
#3
1
you are setting the attr property and not data using .attr('data-location',count)
. to get the attribute you need to use .attr('data-location')
:
您正在使用.attr(“data-location”,count)设置attr属性,而不是数据。要获取属性,需要使用.attr(“data-location”):
var loc = $('.p1').attr('data-location');