[英]Find the value of html table cell by passing column name for a particular row
I am dynamically creating a table using JSON so i dont know in advance how many column and/or rows will be generated.我正在使用 JSON 动态创建一个表,所以我不知道将生成多少列和/或行。
I add a clicked event for the row that get selected.我为被选中的行添加了一个 clicked 事件。
Now my every table will have a column name ID现在我的每个表都会有一个列名ID
I want to find the value of ID for the selected row.我想找到所选行的 ID 值。
How can i achieve this?我怎样才能做到这一点?
I have googled a find a lot of sample which select the cell be index but not by column name.我在谷歌上搜索了很多样本,这些样本选择单元格作为索引而不是列名。
My table is something like:我的表是这样的:
My table is generated like:我的表生成如下:
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + val(array[i][index]) + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
} }
Any help is appreciated任何帮助表示赞赏
I hope i understood you correctly but this should do it.我希望我理解正确,但这应该可以。 It alerts the content of the td with the name ID of the clicked tr.
它用点击的 tr 的名称 ID 提醒 td 的内容。
$('tr').live('click',function(){
alert( $(this).find('td[name="ID"]').html() );
});
To find the td via the th with text ID you could do this:要通过带有文本 ID 的 th 查找 td,您可以执行以下操作:
var index = $('yourtable th:contains("ID")').index();
alert( $('.selectedRow td:eq('+index+')').html() );
What I would do though is to save the ID in the TR's data object so you won't have to pull it out the td but can access it directly, like this:我会做的是将 ID 保存在 TR 的数据对象中,这样您就不必将其从 td 中取出,而是可以直接访问它,如下所示:
[...]
<tr data-id="26"><td>.....</td></tr>
[...]
then you can access it like that:然后你可以像这样访问它:
$('.selectedRow').data('id');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.