简体   繁体   English

使用Javascript动态更改表和行的背景颜色

[英]Changing Background color of a table and rows dynamically using Javascript

Snippet code copied from this link jsfiddle.net/facgwbsm 从此链接jsfiddle.net/facgwbsm复制的代码段代码

I have an app whereby when the user clicks on Add New Item button rows are added dynamically which works fine. 我有一个应用程序,当用户点击添加新项按钮行动态添加,工作正常。 When any number on the table is clicked it is populated dynamically in the rows. 单击表上的任何数字时,它将在行中动态填充。 When I h over over the 1st row the background color changes to green including the corresponding match on the table which works fine . 当我越过第一行时,背景颜色变为绿色,包括表格上相应的匹配,工作正常

I want when other rows are hovered on the effect on the 1st row applies to proceeding rows whereby the background color changes to green on the whole row and the corresponding inputs on the table.. 我希望当其他行悬停在第一行上的效果时应用于前进行,从而整个行上的背景颜色变为绿色,表格上的相应输入变为绿色。

 //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 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>

The functions regarding the input hover and hover out only apply on the first row because the second row isn't created when the code lodes. 有关输入悬停和悬停的功能仅适用于第一行,因为代码排序时不会创建第二行。 You can fix it by adding the last part of your code to the button click: 您可以通过将代码的最后部分添加到按钮单击来修复它:

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");
          }); 
      });
    });

Also, you have another issue: When clicking on numbers before adding a new row, the new row gets empty input boxes. 此外,您还有另一个问题:在添加新行之前单击数字时,新行将获得空输入框。

I am not sure if you really need the id's, I put that in but do not use it functionally as I used classes and thus I had no need to keep the global variables you had. 我不确定你是否真的需要id,我把它放在但是不要在功能上使用它,因为我使用了类,因此我没有必要保留你拥有的全局变量。 I showed how to namespace those but commented them out. 我展示了如何对它们进行命名,但对它们进行了评论。

I had question regarding the new row of inputs and how to determine when you click the tables where the click should place its value thus I added the concept of a focused input row delineated by the class focus-row - I gave it a border color to demonstrate which row is focused. 我对新的输入行有疑问,以及如何确定何时单击应该单击应放置其值的表格,因此我添加了由类focus-row行描绘的焦点输入行的概念 - 我给了它一个边框颜色到证明哪一行是集中的。 When any input in that row is clicked or focused, it sets that focus-row that contains that input. 单击或聚焦该行中的任何输入时,它会设置包含该输入的focus-row

As for the second table and the "bonus" input - I simply used that to highlight using the value from the row being hovered there, not sure how exactly you wished to handle that but this seemed to make the most sense to me. 至于第二个表和“奖金”输入 - 我只是用它突出显示使用那里悬停的行的值,不确定你究竟想要如何处理它,但这似乎对我来说最有意义。

Now, as to the point where you add a new input row, rather than keeping track of the global variables, I simply cloned the first input row and cleared its values and set the id and name attribute there. 现在,关于添加新输入行的点,而不是跟踪全局变量,我只是克隆了第一个输入行并清除了它的值并在那里设置了id和name属性。 Since I attached the event handlers to the wrapper, you are able to add new input rows without dealing with re-attaching. 由于我将事件处理程序附加到包装器,因此您可以添加新的输入行而无需重新附加。

NOTE: you could put the hover on the row using input-group instead of the inputs to avoid "flash" when moving from input to input on the same row but I left that as you had it. 注意:您可以使用input-group而不是input-group将悬停放在行上,以避免在同一行从输入移动到输入时出现“闪烁”,但我将其保留为原样。

I used myApp.wrapper.on('mouseenter', and the mouseleave it really is functionally the same as the .hover but it made it a bit cleaner when I chained in the .on('click focus' for the row focus. You could for example add a button to the input row <button class="set-row-focus">Focus Row</button> or add that class to the input-group and then trigger a custom event on a click of that to the focus/click event handler like this:set event: .on('click focus setfocus' then trigger it $('.set-row-focus').on('click',function(){$(this).siblings('.normal-input').first().trigger('setfocus');}); 我使用了myApp.wrapper.on('mouseenter',mouseleave它在功能上和.hover一样,但是当我在.on('click focus'链接时它会更清晰.on('click focus' 。你。例如,可以在输入行<button class="set-row-focus">Focus Row</button>添加一个<button class="set-row-focus">Focus Row</button>或者将该类添加到input-group ,然后单击该按钮触发自定义事件像这样的焦点/点击事件处理程序:set event: .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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM