我有一张动态生成的表格。在它的行中,我正在放置按钮。
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test()'></td>";
tr = tr + "</tr>";
};
点击按钮,我想获得该行的特定单元格值。例如:如果我点击第一行的年龄,那么我得到的值是50.如果我点击第二行的按钮,那么我应该得到94.
如何在单击按钮时获取表格单元格值?
答案 0 :(得分:1)
以下是动态表的解决方案:
const arryOfPokemons = [{name: 'name1', type: 'type1'}];
function name(pokemon) { return pokemon.name !== 'name' }
function type(pokemon) { return pokemon.type !== 'type' }
const result = [name, type].reduce((result, filterFunc) => result.filter(filterFunc), arryOfPokemons);
因此,通过使用此javascript,您可以获得任何表格单元格的值。
答案 1 :(得分:0)
以下是您的解决方案:
$(document).find('.theButton').on('click',function(){
var age = $(this).parents('tr:first').find('td:eq(1)').text();
console.log(age);
});
答案 2 :(得分:0)
您可以将年龄传递给按钮onclick功能,例如onclick='test('"+resp[i].age +"')'
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test("+resp[i].age +")'></td>";
tr = tr + "</tr>";
};
答案 3 :(得分:0)
使用jQuery尝试此示例,我已使用rowid替换了您的函数测试
https://jsfiddle.net/ucostea/2thyj0ft/
$(document).on("click", ".theButton", function(){
alert("Aage: "+$('.age_'+$(this).attr('rownr')+'').text());
});
for (var i = 0; i < 10; i++) {
var tr = "";
tr = tr + "<tr >";
tr = tr + "<td class='date_"+i+"'>Date" + i + "</td>";
tr = tr + "<td class='age_"+i+"'>Age " + i + "</td>";
tr = tr + "<td class='hour_"+i+"'>Hour " + i + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' rownr='" + i + "'></td>";
tr = tr + "</tr>";
$('.table tbody').append(tr);
};