Javascript 更新jQuery中数据属性的值
我需要在用户每次点击btn时更新数据属性。但它并没有按其应有的方式发挥作用。以下是演示代码:Javascript 更新jQuery中数据属性的值,javascript,jquery,Javascript,Jquery,我需要在用户每次点击btn时更新数据属性。但它并没有按其应有的方式发挥作用。以下是演示代码: $('div.wrapper').on('click', 'div.btn', function(){ var thisGuy = $(this), offset = thisGuy.data('showreplies'); thisGuy.attr('data-showreplies', parseInt(offset) + 10); $('div.dataAt
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
下面是DOM:
<div class="wrapper">
<div class='btn' data-showreplies='10'>Click Me</div>
</div>
<div class="dataAttr"></div>
点击我
我想做的是,当用户单击btn时,数据showreplies attr的值将增加到10,然后它将在div.dataAttr中显示更新后的值,因为每次单击它都会增加
jsiddle链接:尝试更改
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
到
尝试改变
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
到
数据函数也可用作设置器:
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.data('showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
请注意,DOM中的属性保持为10,因为jQuery具有数据值的内部缓存。数据函数也可以用作setter:
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.data('showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
请注意,DOM中的属性保持为10,因为jQuery有一个用于数据值的内部缓存。hmmm。一旦我更改了fiddle上的那些行,它就可以正常工作了hmmm。一旦我更改了fiddle上的那些行,它就可以正常工作了