【问题标题】:Getting the row in which a button is pressed in a HTML table获取在 HTML 表格中按下按钮的行
【发布时间】:2012-12-13 14:49:17
【问题描述】:

我有一张像下面这样的表格

<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。如何获取单击按钮所在行中的那个单元格的值。

我尝试使用表的&lt;tr&gt; 标记创建带有id 属性的表。

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

但是表记录不加id就可以得到吗?

【问题讨论】:

标签: javascript html-table


【解决方案1】:
<script>
function inc()
{
  var val = parseInt(document.getElementById('myid').value);
  val++;
  document.getElementById('myid').value =val;
}
</script>

【讨论】:

  • 还将 id 添加到要增加的 'td' 标记中。
  • 2
【解决方案2】:

如果你可以使用jQuery

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

【讨论】:

    【解决方案3】:

    这里是完整的解决方案,除了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>
    

    【讨论】:

      【解决方案4】:

      使用 jQuery 你可以做到:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-22
        • 1970-01-01
        • 2013-12-25
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        相关资源
        最近更新 更多