Как назначить идентификатор для строки, которая вызывается по нажатию кнопки в JavaScript - PullRequest
0 голосов
/ 24 февраля 2019

Я пытаюсь назначить уникальный идентификатор каждой строке, чтобы затем изменить строки с определенными номерами идентификаторов.Однако, поскольку функция вызывается каждый раз при нажатии кнопки, я всегда получаю один и тот же вывод для числа.Вот моя функция JavaScript

[<script type="text/javascript">
    function insert_row(){
      var firstName = document.getElementById('first_name').value;
      var lastName = document.getElementById('last_name').value;
      var human = "human";
      var id =1;

      var table = document.getElementById("saving_table");

      // Create an empty <tr> element and add it to the 1st position of the table:
      var row = table.insertRow(1);
      row.id=id;
      var rowId = row.id;


      // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      var cell3 = row.insertCell(2);

      // Add some text to the new cells:
      cell1.innerHTML = firstName;
      cell2.innerHTML = lastName;
      cell3.innerHTML = human+ rowId.toString();
       id++;
    }
  </script>][1]

Вот мое объявление таблицы

<div class="container">
 <table class="table table-bordered" id="saving_table">
    <caption>Classmates</caption>
    <thead>
      <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Human or Vampire?</th>
      </tr>
    </thead>
  </table>
  <button class="btn btn-primary" onclick="insert_row()">Submit</button>

, а изображение моего вывода просто инкрустация:

Ответы [ 4 ]

0 голосов
/ 24 февраля 2019

Объявите счетчик вне функции.

Демо

Подробности прокомментированы в демо

// Reference tags
var btn = document.querySelector('button');
var first = document.getElementById('firstName');
var last = document.getElementById('lastName');
var spec = document.getElementById('species');
// Declare counter
var i = 0;

function insert_row(e) {
  // Reference <tbody> (Not <table>)
  var table = document.querySelector("tbody");
  // Insert <tr> (No index is needed)
  var row = table.insertRow();
  // Add ID to <tr>
  row.id = 'r' + i;
  // for every loop...
  for (let c = 0; c < 3; c++) {
    // ...insert a <td>...
    var cell = row.insertCell(c);
    // ...1st loop add the value of first name input as text...
    if (c === 0) {
      cell.textContent = first.value;
      // ...2nd loop add the value of last name input as text...
    } else if (c === 1) {
      cell.textContent = last.value;
      // ...3rd loop add the value of species select as text...
    } else if (c === 2) {
      cell.textContent = spec.value;
      // ...otherwise just end loop
    } else {
      break;
    }
  }
  // Increment counter
  i++;
}
// Add click event handler to button
btn.onclick = insert_row;
table {
  table-layout: fixed;
  width: 75%;
  margin: 10px auto;
}

th {
  width: 33%
}

td {
  text-align: center
}

caption {
  font-size: 1.2rem;
  font-weight: 900;
}

input,
select,
button {
  display: inline-block;
  font: inherit;
  height: 3ex;
  line-height: 3ex;
  vertical-align: middle;
}

select,
button {
  height: 4ex;
}

button {
  float: right
}
<div class="container">
  <table class="table table-bordered" id="saving_table">
    <caption>Classmates</caption>
    <thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Species</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <input id='firstName' placeholder='First'>
  <input id='lastName' placeholder='Last'>
  <select id='species'>
    <option value=''>Species</option>
    <option value='Human &#128373;'>Human &#128373;</option>
    <option value='Vampire &#129499;'>Vampire &#129499;</option>
  </select>
  <button class="btn btn-primary">Submit</button>
</div>
0 голосов
/ 24 февраля 2019

Поскольку переменная id инициализируется при каждом вызове функции, все строки в итоге имеют одинаковый идентификатор (то есть 1).
Одним из способов решения этой проблемы является простое размещение объявления var id = 1; перед началом function insert_row() в качестве глобальной переменной.
Однако, чтобы избежать использования глобальных переменных, мы могли бы получить счетчикиз всех существующих строк таблицы и добавьте к ней 1, чтобы получить новый идентификатор следующим образом:

[<script type="text/javascript">
function insert_row(){
  var firstName = document.getElementById('first_name').value;
  var lastName = document.getElementById('last_name').value;
  var human = "human";

  var table = document.getElementById("saving_table");

  // get count of the number of rows that already exist
  var rowCount = table.getElementsByTagName("tr").length;
  var id = rowCount + 1;

  // Create an empty <tr> element and add it to the 1st position of the table:
  var row = table.insertRow(id);
  row.id=id;
  var rowId = row.id;


  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  // Add some text to the new cells:
  cell1.innerHTML = firstName;
  cell2.innerHTML = lastName;
  cell3.innerHTML = human+ rowId.toString();
   id++;
}

] [1]

HTML-код останется прежним.В случае, если ваше приложение большое или направлено на то, чтобы стать большим проектом, я настоятельно рекомендую использовать второй метод вместо определения глобальной переменной.Глобальные переменные, как правило, становятся очень сложными для управления по мере увеличения размера приложения.

0 голосов
/ 24 февраля 2019

Пожалуйста, сделайте лучший код: 1) увеличивайте insertRow для каждой новой строки 2) не повторяйте все document.getElementById для каждого вызова 3) не смешивайте HTML-код с JS (onclick = "insert_row ()") 4) Если вы сделали СТОЛ с THEAD, используйте TBODY

const
  in_firstName = document.getElementById('first_name'),
  in_lastName  = document.getElementById('last_name'),
  human_str    = "human",
  tableBody    = document.querySelector('#saving_table tbody')
;
var Table_Row_ID = 0;

document.getElementById('insert-row').onclick = function()
{
  // Create an empty <tr> element and add it to the 1st position of the table:
  let row = tableBody.insertRow(Table_Row_ID);
  row.id  = ++Table_Row_ID;

  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
  let
    cell1 = row.insertCell(0),
    cell2 = row.insertCell(1),
    cell3 = row.insertCell(2)
  ;

  // Add some text to the new cells:
  cell1.textContent = in_firstName.value;
  cell2.textContent = in_lastName.value;
  cell3.textContent = human_str + row.id;
}
<div class="container">
  <table class="table table-bordered" id="saving_table">
      <caption>Classmates</caption>
      <thead>
        <tr>
          <th>FirstName</th>
          <th>LastName</th>
          <th>Human or Vampire?</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
</div>
<div class="container">
  <input type="text" id="first_name" placeholder="first_name"   /> 
  <input type="text" id="last_name" placeholder="last_name"   /> 

  <button class="btn btn-primary" id="insert-row">Add Row</button>
</div>
0 голосов
/ 24 февраля 2019

В основном вам просто нужно переместить переменную id за пределы функции.Таким образом, он устанавливается на 1 только когда загружается ваш код, а затем каждый вызов функции увеличивает его.

// global
var id = 1;

function insert_row() {
  // ...

demo

// global
var id = 1;

function insert_row() {
  var firstName = document.getElementById('first_name').value;
  var lastName = document.getElementById('last_name').value;
  var human = "human";

  var table = document.getElementById("saving_table");

  // Create an empty <tr> element and add it to the 1st position of the table:
  var row = table.insertRow(1);
  row.id = id;
  var rowId = row.id;


  // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  // Add some text to the new cells:
  cell1.innerHTML = firstName;
  cell2.innerHTML = lastName;
  cell3.innerHTML = human + rowId.toString();
  id++;
}
<div class="container">
 <table class="table table-bordered" id="saving_table">
    <caption>Classmates</caption>
    <thead>
      <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Human or Vampire?</th>
      </tr>
    </thead>
  </table>
  <input id="first_name" />
  <input id="last_name" />
  <button class="btn btn-primary" onclick="insert_row()">Submit</button>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...