首页 > 解决方案 > 如何在多个表中单击特定列中的行元素时获取表 ID 和值?

问题描述

我需要一些帮助来编写一个 javascript 函数来检索单击的值以及单击多个表中的特定列(层)时的表 ID。

例如,当我单击第 1 层时,我试图将其分配给 tier_token 并根据表 id 设置客户端 --> tier_token=Tier 1, client=products。如果我点击 Tier 2 , tier_token=Tier 1, client=products 。如果我从客户表中单击第 1 层,则 tier_token=Tier 1 和 client=customers,依此类推。

在我的脚本中,我一直在使用document.getElementById,我想要一些可以同时用于多个表 id 的东西,检索该 id 值,并将其设置为变量 client - 因为虽然我只列出了几个表,我需要稍后定义多个表。

另外,我想只允许点击 Tier 列并阻止点击 Points 列。

<html>
<table class="table" id="products">
<tr>
    <th>Tier</th>
    <th>Points</th>
</tr>
    <tr>
    <td>Tier1</td>
    <td>0</td>
  </tr>
   <tr>
    <td>Tier2</td>
    <td>10</td>
  </tr>
   <tr>
    <td>Tier3</td>
    <td>100</td>
  </tr>
</table>
 
  <table class="table" id="customers">
   <tr>
    <th>Tier</th>
    <th>Points</th>
   </tr>
    <tr>
    <td>Tier1</td>
    <td>10</td>
  </tr>
   <tr>
    <td>Tier2</td>
    <td>20</td>
  </tr>
   <tr>
    <td>Tier3</td>
    <td>500</td>
  </tr>
   <tr>
    <td>Tier4</td>
    <td>21</td>
  </tr>
  </table>
</html>

脚本:

<script>
var table = document.getElementById("customers");
    if (table != null) {
        for (var i = 1; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                tableText(this);
            };
        }
    }
    function tableText(tableCell) {
        //alert(tableCell.innerHTML);
        var tier_token=tableCell.innerHTML;
        var client = "customers";
        console.log("Tier:"+ tier_token);
        console.log("Client:"+ client);
        alert("Tier:"+ tier_token + "Client:"+ client);
    }

</script>

标签: javascriptjqueryhtml-table

解决方案


您可以使用$("table td:first-child")选择器,只有在单击第一个 td 时才会调用它,然后在此处理程序中使用.text()来获取单击的 td 的文本并closest('table').attr('id')获取表的 id。

演示代码

//click only on first child(1st columns tds)
$("table td:first-child").on("click", function() {
  var texts = $(this).text(); //get text of td which is clicked
  var ids_ = $(this).closest("table").attr('id') //get clsest table where click event has taken place using that get `id` of table
  console.log("TEXT " + texts + " ID " + ids_)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="products">
  <tr>
    <th>Tier</th>
    <th>Points</th>
  </tr>
  <tr>
    <td>Tier1</td>
    <td>0</td>
  </tr>
  <tr>
    <td>Tier2</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Tier3</td>
    <td>100</td>
  </tr>
</table>
<table class="table" id="customers">
  <tr>
    <th>Tier</th>
    <th>Points</th>
  </tr>
  <tr>
    <td>Tier1</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Tier2</td>
    <td>20</td>
  </tr>
  <tr>
    <td>Tier3</td>
    <td>500</td>
  </tr>
  <tr>
    <td>Tier4</td>
    <td>21</td>
  </tr>
</table>

阅读更多

https://api.jquery.com/closest/

https://api.jquery.com/first-child-selector/

https://api.jquery.com/text/


推荐阅读