Javascript多个递增变量解决方案

时间:2011-06-23 11:36:51

标签: javascript jquery javascript-events increment

我有一个变量ver i = 1

我有一张表格如下;

<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>

该表可能包含更多行。我希望变量在我点击next时将值增加1,为prev减少1。这可以很容易地完成。但我想要一些行依赖的变量。当我点击第一行中的next时,变量值应为2,但在我点击任何其他行中的nextprev时,它不应更改。所有其他行也应如此。变量的最小值应为1.

如果有人向我提供了每行中间单元格中显示的变量的小提琴,将会很有帮助。请注意,在此演示中,它不应该是++--中间单元格中的文本或数据。

Here 是我的小提琴..

提前致谢..

3 个答案:

答案 0 :(得分:1)

$('table tr .next').click(function() {
    alert($(this).closest('tr').index());
});

http://jsfiddle.net/ThiefMaster/5TPCK/2/

顺便说一句,</tr class="testrow">非常错误 - 它应该只是</tr>

答案 1 :(得分:1)

我会使用jQuery.data()将变量存储在每一行中,当用户点击上一个/下一个时更改它:

$(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/

答案 2 :(得分:0)

你不能保留这些计数器的数组(如果预先知道行数和静态,这会有效吗?)否则,您可以使用jquery <tr>函数将计数器附加到每个data()元素。

请参阅:http://api.jquery.com/jQuery.data/

相关问题