【问题标题】:How to manipulate background color of a row and a table using Javascript如何使用 Javascript 操作行和表的背景颜色
【发布时间】:2019-10-11 16:17:16
【问题描述】:

我有一个应用程序,当用户单击“添加新项目”按钮时,使用 Javascript 动态添加行,并且动态添加的行中的每个输入字段都有一个唯一的 id,这很好用。

当点击左侧表格上的任何数字时,它会动态填充到左侧行中。当点击右侧表格上的另一个数字时,它会填充到右侧的单个输入中(加号图标之后)。

当我将鼠标悬停在第一行时,背景颜色变为绿色,包括左侧表格上的相应匹配项,效果很好。

我正在尝试添加一个逻辑 a.) 如果用户点击Add New Item按钮添加新行(该行按照第一行的格式添加)

b.) 在用户单击 2 个表(左右)上的任何 td 数字后,它们的值会动态填充到行中(左侧表上的值填充在 + 符号之前的行中,右侧的值填充表填充在 + 号之后的右表中),当用户将鼠标悬停在行上的值上时,其背景颜色应立即更改并符合他们先前从中选择的表的值...

NB ~ 基本上我希望在单击按钮后动态添加的后续行中模拟第一行的行为(在鼠标悬停后,当从相应的表中填充输入时)。。 p>

JsFiddle 链接: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");
    });
  }
);

【问题讨论】:

    标签: javascript jquery css html-table row


    【解决方案1】:

    当您使用.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>

    【讨论】:

    • 非常感谢 ,, 只是一个礼貌的请求 .. 当我单击添加新输入组按钮添加行时,,,, 我甚至想要添加 + 号之后的最后一个输入字段(以便它与第一行的格式完全相同)...
    • 我更新了我的答案。现在,添加的每一行的元素及其外观都是相同的。行为也是固定的,因此 table2 被突出显示。还可以防止在单击 table1 或 2 时计数器增加,并且没有更多的输入来填充数字。 只是一个旁注:一个好主意是将所有样式放入 css 中并为该元素切换自定义类,这样 javascript 代码更具可读性和更易于使用。
    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多