我试图将表行的值作为字典返回(最好将列名作为键)。但是,我的尝试只能实现所有值的串联字符串。 在我的工作示例中,我返回:
123
但是,我想要实现的是这样的:
{"col1": 1, "col2": 2, "col3": 3}
.
示例代码:
$(document).ready(function() {
$('.clickable-row').click(function() {
var row = $(this).closest('tr').find('*').text();
console.log(row);
return false
});
});
@import 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css';
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<table class="table table-striped table-bordered table-hover" id="results">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr id="clickable-row" class="clickable-row" style="cursor: pointer;">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
最佳答案
这看起来怎么样?
$(document).ready(function() {
$('.clickable-row').click(function() {
var column_names = $("thead").find("th");
var row = $(this).find("td").toArray().reduce(function(previous, current_node, index) {
var text = $(column_names[index]).text();
previous[text] = $(current_node).text();
return previous;
}, {});
console.log(row);
return false
});
});
@import 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css';
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<table class="table table-striped table-bordered table-hover" id="results">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr id="clickable-row" class="clickable-row" style="cursor: pointer;">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
关于jquery - 表中可单击的行,行值作为字典返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470317/