JavaScript multiple incrementing variable solution
I have a variable ver i = 1
.
I have a table as follows;
<table>
<tr class="testrow">
<td class="prev"> </td>
<td class="data"> </td>
<td class="next"> </td>
</开发者_开发知识库tr>
<tr class="testrow">
<td class="prev"> </td>
<td class="data"> </td>
<td class="next"> </td>
</tr>
<tr class="testrow">
<td class="prev"> </td>
<td class="data"> </td>
<td class="next"> </td>
</tr>
<tr class="testrow">
<td class="prev"> </td>
<td class="data"> </td>
<td class="next"> </td>
</tr class="testrow">
<tr>
<td class="prev"> </td>
<td class="data"> </td>
<td class="next"> </td>
</tr>
</table>
The table may have more rows. I want a variable to increase value by 1 when I click next
and decrease by 1 for prev
. This can be done easily. But I want some variable which is row dependent. When I clicknext
in first row, the variable value should be 2, but it should not change when I click either next
or prev
in any other row. Also this should be the case in all other rows. The minimum value of variable should be 1.
It will be helpful if someone provide me a fiddle with the variable displayed in the middle cell of each row. Note that in this demo, it should not be something to ++
or --
the text or data in the middle cell.
Here is my fiddle.
I'd use jQuery.data() to store the variable in each row, changing it when the user clicks prev/next:
$(function() {
$(".testrow").each(function() {
var $row = $(this);
// set the initial value
$row.data("currentIndex", 1);
$row.find(".prev").click(function() {
$row.data("currentIndex", $row.data("currentIndex") - 1);
alert("currentIndex: "+$row.data("currentIndex"));
});
$row.find(".next").click(function() {
$row.data("currentIndex", $row.data("currentIndex") + 1);
alert("currentIndex: "+$row.data("currentIndex"));
});
});
});
jsFiddle: http://jsfiddle.net/5TPCK/12/
$('table tr .next').click(function() {
alert($(this).closest('tr').index());
});
http://jsfiddle.net/ThiefMaster/5TPCK/2/
Btw, </tr class="testrow">
is horribly wrong - it should only be </tr>
.
Couldn't you keep an array of these counters (this would work if the number of rows is known beforehand and static)? Otherwise you could attach the counter to each <tr>
element using the jquery data()
function.
See: http://api.jquery.com/jQuery.data/
精彩评论