Onclick change or insert text in dynamic table cell span

时间:2016-04-04 19:02:09

标签: jquery html

I have a dynamic table, with multiple tr and td and buttons in it. I want to insert a counting number infront of td content, every time the (up)-button is clicked. Something like this: [3 x ABC].

My demo does not work, but my current version; what ever button I click on, the number appears and increase in all of the rows at once. I want the buttons to function in respektiv rows. How to manage that in jquery? Please.

$(function(){
    var count=1;
    $('.up').click(function(){
    count++
    $('.times').text(count+' x ');
})
});

DEMO

1 个答案:

答案 0 :(得分:1)

这一行是问题所在:

$('.times').text(count+' x ');

选择 .times的每个出现次数,并为所有这些事件设置文本。

在您的情况下,您希望同一行上的那个。因此,从点击的元素(this)开始,找到祖先链中最接近的tr。然后,在该行中,再次找到.times以设置文本:

$(this).closest('tr').find('.times').text(count+' x ');

Updated fiddle

如果您还希望每行都有一个计数器,则可以将计数器信息存储在该元素的数据属性中。另一个可以说是更好的解决方案是创建保存变量的闭包。后一个解决方案我已经实现了......

Yet another update of the fiddle