JavaScript 多重自增变量解决方案

标签 javascript jquery increment dom-events

我有一个变量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。

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

Here是我的 fiddle 。

最佳答案

我会使用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/

关于JavaScript 多重自增变量解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6453387/

相关文章:

带有 TCP/IP 通信的 javascript 十六进制代码

jquery - 淡入和/或淡出占位符文本

javascript - 通过查找类和选中的复选框类型来获取自定义属性值的数组

loops - 做不等增量循环

java - Hashmap<Object,Integer> 中的值增量,错误 "Integer cannot be converted to P(object)"Java

php - 在 https URL 中使用基于 http 的 IFRAME

javascript - firebase的updateProfile是否返回Promise中的用户

javascript - jquery scrolltop 仅适用于 jquery < 3.0.0

javascript - 如何在页面加载时打开数据英国模式

web-services - Web 服务返回唯一的自动递增的人类可读 ID 号