开发者

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">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</开发者_开发知识库tr>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr class="testrow">
<tr>
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜