输入更改触发次数太多

Input change trigger too many times

我从一开始就有一个输入字段,我想用它进行计算,在更改值时立即更新。然后我希望能够添加更多输入字段并让它们在编辑内容时更改值,而无需在之后按任何更新按钮。

此代码执行此操作,但现在如果我添加更多输入字段然后编辑第一个输入字段之一,它会多次触发计算函数。我可以删除第 4-6 行(从底部开始)以消除额外的功能触发,但是添加的输入字段将无法即时工作。关于如何解决这个问题的任何想法?

HTML:

<input type="number">
<table>
  <tr>
    <td id="linkedEventList">
      <ol>
      </ol>
      <button id="btn">Add input fields</button>
    </td>
  </tr>
</table>

Jquery/Javascript:

jQuery(function($) {
  $('input').on('input', function(e) {
    calculate();
  });
});

function calculate() {
  alert("Checking how many times this function runs");
}

$(document).ready(function() {
  $("#btn").click(function() {
    $("#linkedEventList ol").append("<li ><input type='text'></input></li>");

    $('input').on('input', function(e) {
      calculate();
    });
  });
  calculate();
});

https://jsfiddle.net/Marbled/mtp9vh3a/1/

您做错了很多事情,请参阅下面的代码并与您的代码进行比较。您没有对任何输入使用 id 并在每次调用用于添加输入的点击处理程序时绑定到所有输入,您只需要绑定到在运行时创建的输入,而不是每次都绑定到所有输入。

var callstofunc = 0;


function calculate() {
  callstofunc++;
  console.log("Checking total count for calculate function called", callstofunc);
}

$(document).ready(function() {
  $('#calculator').on('keydown', function(e) {
    calculate();
  });
  $("#btn").click(function() {
    let countT = $("#linkedEventList ol").find('input').length;
    $("#linkedEventList ol").append("<li ><input type='text' id='input_" + countT + "'></input></li>");

    $("#linkedEventList ol").find('input#input_' + countT).on('keydown', function(e) {
      calculate();
    });
  });
  calculate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="72" id="calculator">
<table>
  <tr>
    <td id="linkedEventList">
      <ol>
      </ol>
      <button id="btn">Add input fields</button>
    </td>
  </tr>
</table>

您只需要绑定处理程序一次即可。您以当前的方式对每次点击进行绑定。此外,您已经在使用 'ready' 快捷方式,因此不需要额外的 document.ready。

jQuery(function($) {

  function calculate() {
    console.log("calculate");
  }

  $("#btn").click(function() {
    $("#linkedEventList ol").append("<li><input type='text'></input></li>");
  });
  
  $(document).on('input','input', function(){
    calculate();
   });
  
  calculate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">
<table>
  <tr>
    <td id="linkedEventList">
      <ol>
      </ol>
      <button id="btn">Add input fields</button>
    </td>
  </tr>
</table>

这是因为每次添加另一个动态输入侦听器时,它也会应用于已经存在的输入。

添加新输入后使用:

$(“input”).eq(($(“input”).length-1)).on(“input”, function(e) {
    //this code only applies to the input event on the last input
    //you can use change, input, keyup/down
    //whichever best fits your case
});