JavaScript在单击按钮时从表格单元格中获取信息

JavaScript get Info from table cells on button click

本文关键字:单元格 获取 信息 表格 单击 按钮 JavaScript      更新时间:2023-09-26

每个表格行都有一个位于单元格中的"Show"按钮。在单击该按钮时,我需要提取文本,包含在该行的其他单元格中。

HTML例子:

<tr>
    <td>1</td>
    <td>Info1</td>
    <td><input class="btn" value="Show" onclick="showRowInfo();" type="button"></td>
</tr>
<tr>
    <td>2</td>
    <td>Info2</td>
    <td><input class="btn" value="Show" onclick="showRowInfo();" type="button"></td>
</tr>
<tr>
    <td>3</td>
    <td>Info3</td>
    <td><input class="btn" value="Show" onclick="showRowInfo();" type="button"></td>
</tr>

我想要的是:当我按下(例如)第三行上的按钮时,提取其他2个单元格("3"answers"Info3")中的文本。我正在寻找在JavaScript中的showRowInfo()的实现,或者至少是一种从所选行中获取单元格的方法。

我将使用单个事件侦听器,而不是为每个按钮设置一个onclick属性。既然您添加了一个jQuery标记,下面的代码应该可以达到这个效果:

$('table').on('click', '.btn', function()
{//replace table selector with an id selector, if you are targetting a specific table
    var row = $(this).closest('tr'),
        cells = row.find('td'),
        btnCell = $(this).parent();
    //set to work, you have the cells, the entire row, and the cell containing the button.
});
<标题>小提琴h1> 果你想在香草ajs中做同样的事情:
document.querySelector('table').addEventListener('click', function(e)
{//same applies here: querySelector('#tableID') would be preferable
    var target = (e = e || window.event).target || e.srcElement;
    if (target.tagName.toLowerCase() === 'input' && target.className.match(/'bbtn'b/))
    {
        var btnCell = target.parentNode,
            row = (function(node)
            {
                while (node.tagName.toLowerCase() !== 'tr')
                    node = node.parentNode;
                return node
            }(btnCell)),
            cells = row.cells;
        //set to work, you have the button-containing cell, the row and all of the cells
    }
}, false);

这种技术被称为事件委托,如果你不熟悉它背后的思想,谷歌一下。

您必须在showRowInfo(this)中通过this

 onclick="showRowInfo(this);"
    function showRowInfo(elm) {
       alert($(elm).closest("tr").find("td:lt(2)").text());
  }