繁体   English   中英

JavaScript多个递增变量解决方案

[英]JavaScript multiple incrementing variable solution

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

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

是我的小提琴。

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

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

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

我使用jQuery.data()将变量存储在每一行中,当用户单击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/

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM