2012-12-13 38 views
1

我有一個像下面獲取其中一個按鈕,在HTML表格按行

<table> 
<tr> 
<td>Item1</td><td>Price-100</td><td>1</td><td><input type="button" value="add one"/> 
</tr> 
<tr> 
<td>Item2</td><td>Price-120</td><td>4</td><td><input type="button" value="add one"/> 
</tr> 
<tr> 
<td>Item3</td><td>Price-90</td><td>2</td><td><input type="button" value="add one"/> 
</tr> 
</table> 

當我點擊一個按鈕,我想增加遞增行的第三個單元格的值表1.我怎樣才能得到該按鈕被點擊的行中的那個單元格的值。

我試圖創建id屬性與表的標記。

var tableRow = $('#tr1').find('td'); 
var origVal = parseInt($(tableRow[2]).text()); 
origVal+=1; 
$(tableRow[2]).text(origVal); 

但是有可能沒有添加id到表記錄?

+2

[你有什麼嘗試?](http://www.whathaveyoutried.com/)請參閱[FAQ](http://stackoverflow.com/faq)。 –

回答

1

如果你可以使用jQuery

$('table input[type="button"]').click(function() { 
     cell = $(this).parent().prev(); 
     cell.text(parseInt(cell.text()) + 1); 
    }); 
0

使用jQuery你可以做:

<script> 
    $('table button').click(function() { 
     var $td = $(this).parent().prev(); 
     var val = parseInt($td.text(), 10) + 1; 
     $td.text(val); 
    }); 
</script> 
2
<script> 
function inc() 
{ 
    var val = parseInt(document.getElementById('myid').value); 
    val++; 
    document.getElementById('myid').value =val; 
} 
</script> 
+1

也會將 id添加到您要增加的「td」標籤。 – 2012-12-13 14:59:10

+1

2 – 2012-12-13 15:00:38

1

下面是完整的解決方案,除了JS功能,您還需要修改您的HTML。

<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    function increment(row) 
    { 
     var row = row -1; 
     var existing_value = Number($('#mytable tr:eq('+row+') > td:eq(2)').text()); 
     $('#mytable tr:eq('+row+') > td:eq(2)').text(existing_value+1) 
    } 
</script> 

<table id="mytable"> 
    <tr> 
     <td>Item1</td><td>Price-100</td><td>1</td><td><input type="button" value="add one" onClick="increment(1);" /> 
    </tr> 
    <tr> 
     <td>Item2</td><td>Price-120</td><td>4</td><td><input type="button" value="add one" onClick="increment(2);" /> 
    </tr> 
    <tr> 
     <td>Item3</td><td>Price-90</td><td>2</td><td><input type="button" value="add one" onClick="increment(3);" /> 
    </tr> 
</table>