1

I have a table that has 5 td tags in it.

<tr id="rows">
    <td x="111" y="1" col="1" row="1">
      <div class="marge-col"></div>
    </td>
    <td x="1" y="1" col="2" row="1">
        <div class="marge-col"></div>
    </td>
    <td x="1" y="1" col="3" row="1">
        <div class="marge-col"></div>
    </td>
    <td x="1" y="1" col="4" row="1">
      <div class="marge-col"></div>
    </td>
    <td x="1" y="1" col="5" row="1">
        <div class="marge-col"></div>
    </td>
</tr>

I want a click on the div.marge-col td tag(parent of clicked div) to increase attr('x') one value(for example, when I click on first.merge-col parent tag(td) increase x attribute and change value to 2) I cannot do it. This is my jquery code, but it's not working. When I click on first div.marge-col console shows me **11**!!! Why??? (1+1=11???)

$(document).on('click','#rows td .marge-col',function(){
                    console.log('col');
                    $(this).parent().attr('x',$(this).parent().attr('x')+1);
                    console.log($(this).parent().attr('x'));
                });
4

2 回答 2

1

因为该属性是一个字符串而不是一个数字,pasrseInt所以使用它作为一个数字,当你添加一个字符串和一个数字时,数字被视为一个字符串并连接到另一个字符串。

$(this).parent().attr('x',parseInt($(this).parent().attr('x'))+1);
于 2013-07-28T10:02:31.683 回答
1

问题是+运算符连接字符串以及执行与数字的加法,并且属性值始终是强的,即使它是数字字符。因此,在递增之前尝试确保“数字”是一个数字:

$(this).parent().attr('x', function (i,x){
    return parseInt(x) + 1;
});
于 2013-07-28T10:03:52.773 回答