在数据属性jquery中获取错误的值 [英] get wrong value in data attribute jquery

查看:117
本文介绍了在数据属性jquery中获取错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据属性的div

i have a div with data attribut like

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

我有像

$('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();

});

数据位置属性上方的脚本将更新为10,但如果我点击按钮再次,数据位置仍为1

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() 要访问 data - * 属性,该属性的值由jQuery在内部缓存, .data() 从那时起使用缓存。使用 .attr()更新属性不会更新缓存,您需要使用 .data()来更新它。这就是为什么你需要使用

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

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

更新它。

这篇关于在数据属性jquery中获取错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆