我正在尝试在jquery中增加一个属性onclick,一次增加1个。
假设我有这个按钮,它是页面上唯一的.new-rcc
:
<a class="new-rcc" data-attr="1" href="#"><span>Button »</span></a>
每次单击按钮时,我需要将data-attr
增加1,因此它会从1增加到2到3到4等等。
我尝试过这样的事情:
var showthese = $('.new-rcc').prop('data-attr');
$('.new-rcc').click(function(){
var showtotal = showthese++;
$(this).prop('data-attr', showtotal);
return false;
});
但它似乎不想工作?
答案 0 :(得分:3)
数据属性不是属性,因此您必须使用attr()
而不是prop()
:
var showthese = $('.new-rcc').data('attr');
$('.new-rcc').click(function(){
showthese++;
$(this).attr('data-attr', showthese);
return false;
});
请注意,您可以使用data()
来获取值,但是使用data()
设置值并不会真正更新属性,它只是由jQuery在内部存储。
答案 1 :(得分:2)
表达式showthese++
的值是原始值showthese
。
您需要预增量运算符(++showthese
),它会计算结果值。