簡體   English   中英

使用Javascript動態更改表和行的背景顏色

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

從此鏈接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>

有關輸入懸停和懸停的功能僅適用於第一行,因為代碼排序時不會創建第二行。 您可以通過將代碼的最后部分添加到按鈕單擊來修復它:

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

此外,您還有另一個問題:在添加新行之前單擊數字時,新行將獲得空輸入框。

我不確定你是否真的需要id,我把它放在但是不要在功能上使用它,因為我使用了類,因此我沒有必要保留你擁有的全局變量。 我展示了如何對它們進行命名,但對它們進行了評論。

我對新的輸入行有疑問,以及如何確定何時單擊應該單擊應放置其值的表格,因此我添加了由類focus-row行描繪的焦點輸入行的概念 - 我給了它一個邊框顏色到證明哪一行是集中的。 單擊或聚焦該行中的任何輸入時,它會設置包含該輸入的focus-row

至於第二個表和“獎金”輸入 - 我只是用它突出顯示使用那里懸停的行的值,不確定你究竟想要如何處理它,但這似乎對我來說最有意義。

現在,關於添加新輸入行的點,而不是跟蹤全局變量,我只是克隆了第一個輸入行並清除了它的值並在那里設置了id和name屬性。 由於我將事件處理程序附加到包裝器,因此您可以添加新的輸入行而無需重新附加。

注意:您可以使用input-group而不是input-group將懸停放在行上,以避免在同一行從輸入移動到輸入時出現“閃爍”,但我將其保留為原樣。

我使用了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