jquery - 表中可单击的行,行值作为字典返回

标签 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>

最佳答案

这看起来怎么样?

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

相关文章:

html - 表格为行应用CSS

html - HTML 表格中的表格

javascript - 动态创建表的 addEventListener 方法

jquery - Flot.js : Customizing legend

jquery - 在 jQuery 中删除父 div 的类

javascript - JS检查getElementById是否存在

javascript - $(window).load(function()) 和 NProgress JQuery 插件。页面已完全加载,但 NProgress 仍在运行

html - 如何在生成的 HTML 表(带有 mysql 数据)中应用 CSS?

html - 文本在粗体悬停时移动

javascript - 访问大层次结构中的深化元素