【问题标题】:Changing Background color of a table and rows dynamically using Javascript使用 Javascript 动态更改表和行的背景颜色
【发布时间】:2019-05-24 16:09:34
【问题描述】:

从这个链接jsfiddle.net/facgwbsm复制的代码片段

我有一个应用程序,当用户单击 添加新项目按钮 时,动态添加行,效果很好。当点击表格上的任何数字时,它会在行中动态填充。当我在第一行上方时,背景颜色变为绿色,包括工作正常的桌子上的相应匹配

我希望当其他行悬停在第一行的效果上时适用于后续行,其中整行的背景颜色变为绿色,表格上的相应输入..

//Code to add child and input fields dynamically
// 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 your 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 code

let currentInput = 1;
let bonusInput = 1;

$("#table1 td").on('click', function(event) {
  //gets the number associated with the click
  let num = $(this).text();
  //set it to input's value attribute
  $("#inp" + currentInput++).attr("value", num);
});

//Bonus input
$("#table2").on('click', function(event) {
  let bon = event.target.textContent;
  $("#bonus" + bonusInput++).attr("value", bon);
});

$("input").hover(function(event) {
    //alert($('#selection1 input').serialize());
    //let num = $(this).attr("value");
    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 tables 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 tables bgcolor on hover out
    $("#table1 td").each(function() {
      $(this).css("backgroundColor", "orange");
    });
  });
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/1.12.4/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="width: 600px; float: right;">
  <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 style="margin-left: 20px;" type="text" name="6" size="4" id="bonus1" value="">
    </div>
  </div>
  <button type="button" id="btn">Add new input group</button>
</div>

Javascript 代码

  //Code to add child and input fields dynamically
        // 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 your 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 code

       let currentInput = 1; 
       let bonusInput = 1;

        $("#table1 td").on('click',function(event){
            //gets the number associated with the click
            let num = $(this).text(); 
            //set it to input's value attribute
            $("#inp" + currentInput++).attr("value",num); 
        });

        //Bonus input
        $("#table2").on('click',function(event){
            let bon = event.target.textContent;
            $("#bonus" + bonusInput++).attr("value",bon);
        });

        $("input").hover( function(event) {
            //alert($('#selection1 input').serialize());
            //let num = $(this).attr("value");
            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","red");
                  //Change tables 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 tables bgcolor on hover out
            $("#table1 td").each(function() {
                $(this).css("backgroundColor","orange");
            }); 
        });
    </script>

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    有关输入悬停和悬停的功能仅适用于第一行,因为第二行不是在代码加载时创建的。您可以通过将代码的最后一部分添加到按钮单击来修复它:

    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 your 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);
    
          $("input").hover( function(event) {
            //alert($('#selection1 input').serialize());
            //let num = $(this).attr("value");
            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 tables 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 tables bgcolor on hover out
              $("#table1 td").each(function() {
                  $(this).css("backgroundColor","orange");
              }); 
          });
        });
    

    另外,您还有一个问题: 在添加新行之前单击数字时,新行将获得空输入框。

    【讨论】:

    • 试过你的代码,但它不起作用,显示计数错误未在控制台选项卡中定义
    • 这只是我更改的代码的一部分。您仍然需要代码的开头(声明计数的位置)和结尾。
    【解决方案2】:

    我不确定你是否真的需要 id,我把它放进去,但没有像我使用类一样在功能上使用它,因此我不需要保留你拥有的全局变量。我展示了如何为它们命名,但将它们注释掉。

    我对新的输入行以及如何确定何时单击应放置其值的表有疑问,因此我添加了由 focus-row 类描述的焦点输入行的概念 - 我给了它一个边框颜色以显示哪一行被聚焦。当单击或聚焦该行中的任何输入时,它会设置包含该输入的 focus-row

    至于第二个表和“奖金”输入 - 我只是用它来突出显示悬停在那里的行中的值,不确定您希望如何处理,但这似乎对我来说最有意义.

    现在,至于添加新输入行的位置,而不是跟踪全局变量,我只是克隆了第一个输入行并清除其值并在那里设置 id 和 name 属性。由于我将事件处理程序附加到包装器,因此您无需处理重新附加即可添加新的输入行。

    注意:您可以使用 input-group 而不是输入将鼠标悬停在该行上,以避免在同一行上从一个输入移动到另一个输入时出现“闪烁”,但我保留了它。

    我使用了myApp.wrapper.on('mouseenter',mouseleave,它在功能上确实与.hover 相同,但是当我将.on('click focus' 链接到行焦点时,它让它变得更简洁了。例如,您可以将按钮添加到输入行 &lt;button class="set-row-focus"&gt;Focus Row&lt;/button&gt; 或将该类添加到 input-group,然后在单击该类时触发自定义事件到焦点/单击事件处理程序,如下所示:设置事件:.on('click focus setfocus'然后触发它$('.set-row-focus').on('click',function(){$(this).siblings('.normal-input').first().trigger('setfocus');});

    $(function() {
      // namespace globals
      var myApp = myApp || {
        //count: 5,
        //currentInput: 1,
        // bonusInput: 1,
        wrapper: $('#wrapper'),
        table1: $("#table1"),
        table2: $("#table2")
      };
    
      $('#btn').on('click', function(event) {
        //Code to add child and input fields dynamically
        const groups = myApp.wrapper.find('.input-group');
        const newGroup = groups.first().clone(true).removeClass('focus-row');
        newGroup.find('input')
          //only if you really need id's
          .each(function(index) {
            let newId = $(this).is(".normal-input") ? "inp" + groups.length + index : "bonus" + groups.length;
            $(this).attr("name", newId)
              .attr("id", newId).val('');
          });
        newGroup.appendTo(myApp.wrapper);
      });
    
      myApp.table1.on('click', 'td', function(event) {
        //gets the number associated with the click
        let num = $(this).text();
        $('.focus-row').find('.normal-input').filter(function() {
          return this.value.length === 0;
        }).first().val(num);
      });
    
      //Bonus input
      myApp.table2.on('click', 'td', function(event) {
        let bon = $(this).text();
        $('.focus-row').find('.bonus-input').val(bon);
      });
      myApp.wrapper.on('mouseenter', 'input', function(event) {
          let inputs = $(this).closest('.input-group')
            .find('input')
            .filter(function(index) {
              return !!($(this).val());
            })
            .each(function(index) {
              let num = $(this).val();
              //Change input color on hover
              $(this).toggleClass('mark-hover', true);
              let pairTable = {};
              if ($(this).is('.normal-input')) {
                pairTable = myApp.table1;
              }
              if ($(this).is('.bonus-input')) {
                pairTable = myApp.table2;
              }
              pairTable.find('td')
                .filter(function(index) {
                  return $(this).text() == num;
                })
                .toggleClass('mark-hover', true);
    
            });
        }).on('mouseleave', 'input', function(event) {
          //remove class on hover out
          $(this).closest('.input-group')
            .find('input')
            .toggleClass('mark-hover', false);
          //removes class in tables on hover out
          myApp.table1.add(myApp.table2)
            .find('td')
            .toggleClass("mark-hover", false);
        })
        // sets the focus row
        .on('click focus', 'input', function() {
          $('.input-group').removeClass('focus-row');
          $(this).closest('.input-group')
            .addClass('focus-row')
        });
    });
    table {
      border-collapse: collapse;
      border: 5px solid black;
      width: 100%;
    }
    
    .table-wrapper {
      width: 140px;
      float: left;
    }
    
    .inputs-container {
      width: 100%;
      float: right;
    }
    
    .inputs-container input {
      margin-right: 0.3em;
    }
    
    .inputs-container .bonus-input {
      margin-left: 20px;
    }
    
    .focus-row {
      border: solid 1px lime;
    }
    
    td {
      width: 50%;
      height: 2em;
      border: 1px solid #ccc;
      background-color: orange;
      text-align: center;
      vertical-align: middle;
      font-weight: bold;
      cursor: pointer;
    }
    
    td.mark-normal {
      background-color: orange;
    }
    
    .mark-hover {
      background-color: lightgreen;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!--Table on the left -->
    <div class="table-wrapper">
      <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 class="table-wrapper" style="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 class="inputs-container">
      <div id="wrapper">
        <div class="input-group focus-row">
          <input class="normal-input" type="text" name="1" size="4" id="inp1" value="">
          <input class="normal-input" type="text" name="2" size="4" id="inp2" value="">
          <input class="normal-input" type="text" name="3" size="4" id="inp3" value="">
          <input class="normal-input" type="text" name="4" size="4" id="inp4" value="">
          <input class="normal-input" type="text" name="5" size="4" id="inp5" value=""> +
          <input class="bonus-input" type="text" name="6" size="4" id="bonus0" value="">
        </div>
      </div>
      <button type="button" id="btn">Add new input group</button>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-05
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多