单击时jquery未返回正确的值

时间:2018-01-01 19:29:52

标签: javascript jquery ajax html5 attributes

我正在更新/添加ajax成功的数据属性。但问题是我使用点击处理程序获取更新的值。

Ajax成功更新值。

            success: function(data) {            
               if (data) {
                  var max = container.find('.xyz').data('max');
                  rooty.attr('data-max', max);
                }
            }

我没有获得点击的更新值。

    $(document).on('click', '.ash_loadmore:not(.disabled)', function(event) {
       var me = $(this);
       var button = me.parent().parent();
       var cat = button.data('max');
    });

我已经有了这个标记

<div class="container" data-max="5"></div>

我只是使用ajax success回调更新值(5)。虽然它更新了值,但我仍然得到原始值(5)而不是更新的值。

1 个答案:

答案 0 :(得分:0)

rooty.attr('data-max', max);

您正混用data()attr()的用法。 jQuery的工作方式,一旦你调用data(key)它就会缓存该值,这是出于性能的考虑。如果以后使用attr()更改了值,则不会更新内部jQuery缓存,因此后续调用data(key)将返回缓存中的内容。

要避免这种情况,请坚持使用data()方法获取和设置数据属性,因为使用data(key, value)设置值会更新内部缓存。

rooty.data('max'); //getter
rooty.data('max', max); //setter

&#13;
&#13;
var $div = $('div');

console.log($div.attr('data-key'));
console.log($div.data('key'));

$div.attr('data-key', 'two');
console.log($div.attr('data-key')); //prints 'two' as that is the attr value
console.log($div.data('key')); //prints 'one' as that's the cache value

$div.data('key', 'three');
console.log($div.attr('data-key')); //prints 'two' as that's still the attr value
console.log($div.data('key')); //prints 'three' as that's the cache value
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="one"></div>
&#13;
&#13;
&#13;