使用Javascript

时间:2019-05-24 16:09:34

标签: javascript jquery css

从此链接jsfiddle.net/facgwbsm复制的代码段

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

我希望在第一行的效果上悬停其他行时,将其应用于行,从而背景颜色在整行和表上的相应输入上变为绿色。

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

2 个答案:

答案 0 :(得分:0)

有关输入悬停和悬停的功能仅适用于第一行,因为在代码断开时未创建第二行。您可以通过将代码的最后部分添加到单击按钮的方式来解决此问题:

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

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

答案 1 :(得分:0)

我不确定您是否真的需要id,我把它放进去了,但是由于我使用了类,所以没有在功能上使用它,因此我不需要保留您拥有的全局变量。我展示了如何命名这些名称空间,但将其注释掉了。

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

关于第二张表和“奖励”输入-我只是简单地使用它来突出显示悬停在那儿的行中的值,不确定要如何精确地处理它,但这对我来说似乎最有意义

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

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

我使用了myApp.wrapper.on('mouseenter',mouseleave,它在功能上实际上与.hover相同,但是当我将.on('click focus'链接到该行时,它变得更加干净焦点。例如,您可以将按钮添加到输入行<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>