Найти значения в ячейках таблицы с помощью Javascript - PullRequest
0 голосов
/ 19 января 2019

Я использую динамическую таблицу в 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) {
.
.
.
}

1 Ответ

0 голосов
/ 19 января 2019

Добро пожаловать в переполнение стека. Рассмотрим следующий код.

$(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(), вы можете перебирать каждую строку и сравнивать значения. Переменная может использоваться в качестве флага, чтобы указать, была ли найдена игла в стоге сена. Если не найдено, вы можете добавить строку. В противном случае не добавляйте строку.

Надеюсь, это поможет.

...