Как манипулировать цветом фона строки и таблицы с помощью Javascript - PullRequest
0 голосов
/ 25 мая 2019

У меня есть приложение, при котором, когда пользователь нажимает кнопку «Добавить новый элемент», строки добавляются динамически с использованием Javascript, и каждое поле ввода в добавляемой строке динамически имеет уникальный идентификатор, и это прекрасно работает.

При нажатии любого числа в таблице слева оно динамически заполняется в строке слева.При щелчке другого числа в таблице справа он заполняет один вход справа (после значка плюса).

При наведении курсора на 1-ю строку цвет фона меняется на зеленый, включая соответствующее совпадениев таблице слева, которая работает нормально.

Я пытаюсь добавить логику, при которой а.) если пользователь нажимает кнопку Добавить новый элемент, чтобы добавить новую строку (строка добавляется в соответствии сформат 1-й строки) .

b.) После того, как пользователь нажимает на любое число td в 2 таблицах (справа и слева) и их значения заполняются в строках динамически (значение налевая таблица заполняется в строке перед знаком «+», а значение в правой таблице заполняется в правой таблице после знака «+»), когда пользователь наводит курсор на значения в строках, их цвет фона должен немедленно измениться и соответствовать значениям таблиц, которые онранее были выбраны из ...

NB ~ В основном я хочу поведение в 1-й строке (после наведения мыши, когдаn входов заполняются из соответствующих таблиц) для имитации в последующих строках, которые динамически добавляются после нажатия кнопки .

JsFiddle link: Js Fiddle

~ Пожалуйста, помогите в этой довольно сложной задаче ..

Javascript код, который комментируется, чтобы показать мои шаги в задаче

//Add row input fields dynamically on button click
// Starting number of inputs
let count = 5;

// Wrapper
const wrapper = document.querySelector("#wrapper");

document.querySelector("#btn").addEventListener("click", () => {
  const container = document.createElement("div");

  for (let i = 0; i < 5; i++) {
    // Increment the count to ensure that it is unique
    count++;

    // Create new `<input>` element
    const input = document.createElement("input");
    input.type = "text";
    input.name = count;
    input.size = "4";
    input.id = `inp${count}`;

    container.appendChild(input);

    // Optional: add empty whitespace after each child
    container.append(document.createTextNode(" "));
  }
  wrapper.appendChild(container);
});
//END creating rows dynamically

let currentInput = 1;
let bonusInput = 1;

//Left table on click event
$("#table1 td").on("click", function(event) {
  //gets the number associated with the click
  let num = $(this).text();
  //Populate it in 1st row input fields (before plus sign)
  $("#inp" + currentInput++).attr("value", num);
});

//Right table on click event
$("#table2").on("click", function(event) {
  //gets the number associated with the click
  let bon = event.target.textContent;
  //Populate it in 1st row input fields (after plus sign)
  $("#bonus" + bonusInput++).attr("value", bon);
});

//Manipulate background colors of rows with corresponding tables they were
//selected on hover in and hover out
$("input").hover(
  function(event) {
    let parent = $(this).parent();
    $(parent.children()).each(function(index, element) {
      let num = $(element).val();
      //console.log(num);
      if (num) {
        //Change input color on hover
        $(this).css("backgroundColor", "green");
        //Change left table bgcolor on hover
        $("#table1 td").each(function() {
          if ($(this).text() === num) $(this).css("backgroundColor", "green");
        });
        // $("#table2 td").each(function() {
        //     if ($(this).text() === num) $(this).css("backgroundColor","green");
        // });
      }
    });
  },
  function(event) {
    //Change input color on hover out
    let parent = $(this).parent();
    $(parent.children()).each(function(index, element) {
      $(element).css("backgroundColor", "white");
    });
    //Change left table bgcolor on hover out
    $("#table1 td").each(function() {
      $(this).css("backgroundColor", "orange");
    });
  }
);

1 Ответ

0 голосов
/ 25 мая 2019

Когда вы используете .hover() -helper, слушатели событий создаются и привязываются к элементам, которые доступны на момент создания. Все входы, созданные после этого, игнорируются. Вы должны назначить / активировать поведение при наведении на них при создании / добавлении новых входных данных.

//Add row input fields dynamically on button click
// Starting number of inputs
let count = 0;

// Wrapper
const wrapper = document.querySelector('#wrapper');

document.querySelector('#btn').addEventListener('click', () => {

  // Increment the count to ensure we have unique inputs
  count++;

  const container = document.createElement('div');
          
  for (let i = 1; i <= 5; i++) {
    let input_index = (count * 5) + i;
    
    // Create new `<input>` element
    const input = document.createElement('input');
    input.type = 'text';
    input.name = input_index;
    input.size = '4';
    input.id = `inp${input_index}`;

    $(input).hover(onInputHoverIn, onInputHoverOut);

    container.appendChild(input);
            
    // Optional: add empty whitespace after each child
    container.append(document.createTextNode(' '));
  }
  
  // Bonus-Input
  container.append(document.createTextNode(' + '));

  let input_index = count + 1;
  // Create new `<input>` element
  const input = document.createElement('input');
  input.type = 'text';
  input.name = `bonus${input_index}`;
  input.size = '4';
  input.style.marginLeft = '20px';
  input.id = `bonus${input_index}`;
  
  $(input).addClass('bonus-input');
  $(input).hover(onInputHoverIn, onInputHoverOut);

  container.appendChild(input);
  
  wrapper.appendChild(container);
});
//END creating rows dynamically

let currentInput = 0; 
let bonusInput = 0;

//Left table on click event
$("#table1 td").on('click',function(event){
  if (currentInput >= ((count + 1) * 5)) {
    return;
  }
  currentInput++;
  //gets the number associated with the click
  let num = $(this).text(); 
  //Populate it in 1st row input fields (before plus sign)
  $("#inp" + currentInput).attr("value",num); 
});

//Right table on click event
$("#table2").on('click',function(event){
  if (bonusInput >= (count + 1)) {
    return;
  }
  bonusInput++;
  //gets the number associated with the click
  let bon = event.target.textContent;
  //Populate it in 1st row input fields (after plus sign)
  $("#bonus" + bonusInput).attr("value",bon);
});

//Manipulate background colors of rows with corresponsing tables they were
//selected on on hover in and hover out
function onInputHoverIn(event) {
  let parent = $(this).parent();
  $(parent.children()).each(function (index, element) {
    let num = $(element).val();
    let isBonus = $(element).hasClass('bonus-input');
    //console.log(num);
    if (num) {
      //Change input color on hover
      $(this).css("backgroundColor","green");
      if (!isBonus) {
        //Change left table bgcolor on hover
        $("#table1 td").each(function() {
          if ($(this).text() === num) $(this).css("backgroundColor","green");
        });
      } else {
        //Change left table bgcolor on hover
        $("#table2 td").each(function() {
          if ($(this).text() === num) $(this).css("backgroundColor","green");
        });
      }
      }
    });
}
function onInputHoverOut(event) {
    //Change input color on hover out
    let parent = $(this).parent();
    $(parent.children()).each(function (index, element) {
      $(element).css("backgroundColor","white");
    });
    //Change left table bgcolor on hover out
    $("#table1 td, #table2 td").each(function() {
      $(this).css("backgroundColor","orange");
    }); 
};
$("input").hover(onInputHoverIn, onInputHoverOut);
table {
  border-collapse: collapse;
  border: 5px solid black;
  width: 100%;
}
td {
  width: 50%;
  height: 2em;
  border: 1px solid #ccc;
  background-color:orange;
  text-align:center;
  vertical-align:middle;
  font-weight:bold;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!--Table on the left -->
<div style="width: 140px; float: left;">
  <table id="table1">
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>5</td>
        <td>6</td>
      </tr>
      <tr>
        <td>7</td>
        <td>8</td>
      </tr>
      <tr>
        <td>9</td>
        <td>10</td>
      </tr>
    </tbody>
  </table>
</div>
<!-- Rows on the right-->

    
<!--2nd table-->
<div style="width: 140px; float: left; margin-left: 12px;">
  <table id="table2">
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>5</td>
        <td>6</td>
      </tr>
      <tr>
        <td>7</td>
        <td>8</td>
      </tr>
      <tr>
        <td>9</td>
        <td>10</td>
      </tr>
    </tbody>
  </table>
</div>
<!-- Rows on the right-->

<!-- Make sure each input has a unique id-->
<div style="clear: both;">
  <div id="wrapper">
    <div>
      <input type="text" name="1" size="4" id="inp1" value="">
      <input type="text" name="2" size="4" id="inp2" value="">
      <input type="text" name="3" size="4" id="inp3" value="">
      <input type="text" name="4" size="4" id="inp4" value="">
      <input type="text" name="5" size="4" id="inp5" value="">  +
      <input class="bonus-input" style="margin-left: 20px;" type="text" name="bonus1" size="4" id="bonus1"  value="">  
    </div>
  </div>
  <button type="button" id="btn">Add new input group</button>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...