JavaScript在单击按钮时从表格单元格中获取信息
JavaScript get Info from table cells on button click
每个表格行都有一个位于单元格中的"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());
}
相关文章:
- 从Javascript中选定的行中获取特定单元格的值
- 使用JavaScript获取Gridview单元格值
- jQuery如何获取td单元格值
- 获取关联单元格onchange的值
- 无法使用document.getElementById获取动态生成的单元格的值
- 正在获取IE中的表单元格内容
- 获取命名单元格的行和列索引
- 如何使用javascript从动态表中获取特定的单元格值
- 如何获取嵌入在单元格中的文本框的值
- 如何使用jquery获取表单元格中子元素的值
- 仅使用 PHP 获取表单元格值,没有 ajax
- 在javascript中第一次单击行时获取表单元格值
- 获取HTML表中单击的列中第一个单元格和单击的行中第一个单元的内容
- 获取表中某个单元格的列索引和行索引
- 如何获取gridPanel单元格值?ExtJs
- 在单元格编辑时获取extjs中的行数据
- 如何从HTML表中的多个单元格获取复选框
- 从HTMLTableRowElement中的特定单元格获取子元素并隐藏/删除它们
- 从Google Drive电子表格单元格获取数据
- RadGrid-从客户端从特定单元格获取对象