javascript - 根据单击的链接更改表格内容

标签 javascript jquery html mysql ajax

我有 2 个 HTML 表格。我正在尝试根据第一个表中按下的链接来更改第二个表的内容。

下面是填充第一个表的代码:

$.each(tableResults, function () {
  $('#table1 tbody:last-child').append('<td>' + this + '</td>'); 
});

下面是填充第二个表的代码:

$(document).ready(function () {
  var tableName = 'databaseTable1';
  $.ajax({
    url: 'http://localhost/api/Dynamic?table=' + tableName, 
    dataType: 'Json',
    success: function (tableResults) {
      $.each(tableResults, function (index, value) {
        if ($('#table2 th:last-child').length === 0) {
          $('#table2 thead').append('<th>' + value + '</th>');
        } else {
          $('#table2 th:last-child').after('<th>' + value + '</th>');
        }
      });
    }
  });
});

如您所见,表格是动态填充的。我需要知道如何将第一个表中的每个值转换为一个链接,该链接将变量 tableName 更改为所选值。

然后页面应刷新并显示所选表中的数据。如果它有助于我的程序有一个 F# 后端。

还有一个旁注,有谁知道如何将 tableNames 默认值设置为 table1 中的第一个值。

如有任何帮助,我们将不胜感激。

最佳答案

您可以将tableName 存储在触发器元素的属性中(例如a)。然后,当用户单击此触发器时,使用 .attr() 从属性中获取 tableName .

我不知道你的 react ,所以在我的例子中有一个虚拟的。

(点击任意一行,查看日志中的tableName

var tableResults = [
  {
    name: 'dynamicTable1'
  },
  {
    name: 'dynamicTable2'
  }
];

$.each(tableResults, function () {
  $('#table1 tbody:last-child').append('<tr><td><a data-table="' + this.name + '">' + this.name + '</a></td></tr>'); 
});

$(document).on('click','[data-table]', function(){
  var link = $(this),
      tableName = link.attr('data-table');

  console.log(tableName);

  // do your ajax call with tableName
  // $.ajax({ ....
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table id="table1">
  <tbody></tbody>
</table>
<hr />
<table id="table2">
  <tbody></tbody>
</table>

http://jsbin.com/jicihohama/edit?html,js,console,output

注意事项:

  1. The page should then refresh and display the data

    刷新是指ajax“刷新”吗?否则为什么需要 ajax?

  2. 你不能把td放在tbody里,所以你也需要添加一行(tr)。

关于javascript - 根据单击的链接更改表格内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39891739/

相关文章:

c# - 在 JS 中访问 Asp.Net Session 变量

javascript - 如何遍历 JavaScript 对象的键

javascript - 返回 $.getJSON 函数的结果

javascript - SetTimeout + fs.writeFile 删除我的对象

javascript - jQuery 移动按钮有时只会被选中,但不会发生页面转换

javascript - MM/DD 验证。它没有 YYYY 也应该验证 02/30 我也不能

jQuery DOM 遍历最佳实践

Javascript循环嵌套点击事件

html - 图像未出现在 HTML 中,而是出现在 Inspector 中?

html - 主菜单 html 化