1

我有一张如下表

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

当我单击一个按钮时,我想将行的第 3 个单元格的值增加 1。如何获取单击按钮所在行中的那个单元格的值。

我尝试使用带有<tr>表标签的 id 属性创建。

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

但是是否可以在不向表记录添加 id 的情况下获取?

4

4 回答 4

2
<script>
function inc()
{
  var val = parseInt(document.getElementById('myid').value);
  val++;
  document.getElementById('myid').value =val;
}
</script>
于 2012-12-13T14:57:57.583 回答
1

如果你可以使用jQuery

$('table input[type="button"]').click(function() {
        cell = $(this).parent().prev();
        cell.text(parseInt(cell.text()) + 1);
    });
于 2012-12-13T14:57:19.510 回答
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>
于 2012-12-13T15:05:15.693 回答
0

使用 jQuery,您可以:

<script>
    $('table button').click(function() {
        var $td = $(this).parent().prev();
        var val = parseInt($td.text(), 10) + 1;
        $td.text(val);
    });
</script>
于 2012-12-13T14:52:44.887 回答