2013-07-28 65 views
1

我有一個表中有5個td標籤。當用jquery點擊元素時增加新的屬性

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

我要上div.marge-col td標籤(點擊DIV的母公司)點擊來增加attr('x')一個值(例如,當我點擊first.merge-col父標籤(TD)的增加量X屬性和值更改爲2) 我做不到。 這是我的jQuery代碼,但它不工作。 當我點擊第一個div.marge-col控制檯顯示我**11** !!!爲什麼??? (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')); 
       }); 

回答

1

因爲屬性是一個字符串不是數字,則使用pasrseInt使用它作爲一個數字,當添加一個字符串和一個數目的數目被視爲字符串並連接到另一個字符串。

$(this).parent().attr('x',parseInt($(this).parent().attr('x'))+1); 
1

的問題是,+運營商連接字符串,以及執行加法與數字和屬性值始終是一個強大的,即使它是一個數字字符。因此,請確保「數字」在遞增之前是一個數字:

$(this).parent().attr('x', function (i,x){ 
    return parseInt(x) + 1; 
});