首页 > 解决方案 > 使用 Javascript 在表格单元格中查找值

问题描述

我在 HTML 中使用动态表,但我需要验证这些值是否重复。我正在尝试使用单元格内的值而不是文本来执行此操作。这些是价值观以及我到目前为止所拥有的:

 var tBody = $("#tablaAplicaciones > TBODY")[0];
 //Add Row.
 var row = tBody.insertRow(-1);

 //Add Name cell.
 var cell = $(row.insertCell(-1));
 cell.html(nameCountry);
 cell.val(idCountry);

 //Add Country cell.
 cell = $(row.insertCell(-1));
 cell.html(nameCompany);
 cell.val(idCompany);


if (($('#tablaApp tr > td:contains(' + countryName + ') + td:contains(' + companyName + ')').length) == 1) {
.
.
.
}

标签: javascriptjqueryhtml-table

解决方案


欢迎来到堆栈溢出。考虑以下代码。

$(function() {
  var idCountry = "9";
  var nameCountry = "United States";
  var idCompany = "9";
  var nameCompany = "Genentech";

  var tBody = $("#tablaAplicaciones > tbody");

  //Create Row
  var row = $("<tr>");

  //Add Country cell to Row
  $("<td>", {
      class: "name-country"
    })
    .data("id", idCountry)
    .html(nameCompany)
    .appendTo(row);

  //Add Company cell to Row
  $("<td>", {
      class: "name-company"
    })
    .data("id", idCompany)
    .html(nameCompany)
    .appendTo(row);

  // Assume vales are not in the table
  var found = -1;

  $("tr", tBody).each(function(i, el) {
    // Test each row, if value is found set test to tue
    if ($(".name-country", el).text().trim() == nameCountry) {
      found = i;
    }
    if ($(".name-company", el).text().trim() == nameCompany) {
      found = i;
    }
  });

  if (found == -1) {
    // If test is false, append the row to table
    row.appendTo(tBody);
    console.log("Row Added", row);
  } else {
    console.log("Values already in Table, row: " + found);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaAplicaciones">
  <thead>
    <tr>
      <th>Country</th>
      <th>Company</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-id="1" class="name-country">United States</td>
      <td data-id="1" class="name-company">Apple Inc.</td>
  </tbody>
</table>

使用.each(),您可以遍历每一行并比较值。变量可以用作标志来指示是否在大海捞针中找到了针。如果没有找到,您可以追加该行。否则,不要添加该行。

希望有帮助。


推荐阅读