表中可点击的行,其中行值作为字典返回

时间:2018-11-25 18:01:00

标签: jquery html-table

我试图将表行的值作为字典返回(最好将列名作为键)。但是,我的尝试仅实现了所有值的串联字符串。 在我的工作示例中,我返回:

  

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>

1 个答案:

答案 0 :(得分:2)

这看起来如何?

$(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>