[英]jquery on click is not returning correct value
我正在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成功回调来更新value(5)。 虽然它更新了值,但我仍在获取原始值(5),而不是更新的值。
rooty.attr('data-max', max);
您正在混合使用data()
和attr()
。 jQuery的工作方式是,一旦调用data(key)
,出于性能考虑,它将缓存该值。 如果稍后使用attr()
更改了值,则内部jQuery缓存不会更新,因此后续对data(key)
调用将返回缓存中的内容。
为避免这种情况,请坚持使用data()
方法获取和设置数据属性,因为使用data(key, value)
设置data(key, value)
确实会更新内部缓存。
rooty.data('max'); //getter
rooty.data('max', max); //setter
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
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-key="one"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.