我的变量将自身添加到自身时遇到问题。

变量以0开头,然后将1添加到自身,然后不再执行。
我想知道是否有人对如何解决此问题有任何想法,因为我的主要问题是该变量不能为全局变量,因此将使用多个变量。该表是12x24,表示有很多td

例:


  如果单击td:nth-​​child(1),它将使用其他变量
  与td:nth-​​child(5)相比


所以到目前为止,这是我的代码(jsFiddle):

jQuery的:

$('table.masteries tr.p0 td').on('click', function(){
    i = 0
    s = $(this).find('p').text()
    current_max = parseInt(s.substr(s.length - 1))
    if (
        $(this).is($(':nth-child(1)'))
        || $(this).is($(':nth-child(2)'))
        || $(this).is($(':nth-child(3)'))
        || $(this).is($(':nth-child(4)'))
    ) {
        i = i + 1 /<-- the issue
        console.log(i) /<-- the issue
        $(this).closest('span').append(i); /<-- the issue
    } else if (
        $(this).is($(':nth-child(5)'))
        || $(this).is($(':nth-child(6)'))
        || $(this).is($(':nth-child(7)'))
        || $(this).is($(':nth-child(8)'))
    ) {

    } else if (
        $(this).is($(':nth-child(9)'))
        || $(this).is($(':nth-child(10)'))
        || $(this).is($(':nth-child(11)'))
        || $(this).is($(':nth-child(12)'))
    ) {

    }
});


HTML片段:

<table class="masteries" border="1">
        <tr class="p0">
            <td><p><span>0</span>/1</p></td>
            <td><p><span>0</span>/4</p></td>
            <td><p><span>0</span>/4</p></td>
            <td><p><span>0</span>/1</p></td>

            <td><p><span>0</span>/2</p></td>
            <td><p><span>0</span>/2</p></td>
            <td><p><span>0</span>/2</p></td>
            <td><p><span>0</span>/2</p></td>

            <td><p><span>0</span>/1</p></td>
            <td><p><span>0</span>/3</p></td>
            <td><p><span>0</span>/3</p></td>
            <td><p><span>0</span>/1</p></td>
        </tr>
</table>

最佳答案

更改

i = 0




if(!i){
   i = 0;
}


因此,如果已设置i,则不会将其重置为0。

更新资料

您还需要将所有i实例更改为this.i,因为i是本地函数变量,每次关闭回调函数时都会丢失。

Updated fiddle

10-07 19:04
查看更多