首页 > 解决方案 > 我的 jQuery 片段识别手动输入,但不是 onClick 输入

问题描述

我正在尝试总结我的表单字段。如果我手动插入该值,它就可以工作。但是当我单击按钮添加值时,它不会。我相信我应该在 jQuery 部分改变一些东西,但我不知道是什么。有人有想法吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>

<script type="text/javascript">
$('form#lines-form-1 :input').change(function() {
  var tot = 0;
  $("form#lines-form-1 :input").each(function() {
    tot += Number($(this).val());    
  });
  $('#tot-qty').text(tot);
});
</script>

<script>
   function changeValueA(x){
     document.getElementById('i1').value=x.innerHTML;
    }
    function changeValueB(x){
     document.getElementById('i2').value=x.innerHTML;
    }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>
    <text>Field A</text>
    <button id="80" onclick="changeValueA(this)">80</button>
    <button id="50" onclick="changeValueA(this)">50</button>
</div>

<div>
    <text>Field B</text>
    <button id="80" onclick="changeValueB(this)">80</button>
    <button id="50" onclick="changeValueB(this)">50</button>
</div>


<form id="lines-form-1">
  <label>Field A</label>
  <input type="text" id="i1" name="i1">
  <br>
  <label>Field B</label>
  <input type="text" id="i2" name="i2">
  <br>
</form>

<div id="tot-qty">0</div>

标签: javascriptjquery

解决方案


问题是因为手动更改input直通代码的值不会引发任何事件。因此,change您为更新总数而创建的事件侦听器永远不会触发。要解决此问题,您可以在更新值后手动trigger()设置事件。

另请注意,使用不显眼的事件处理程序而不是内联事件处理程序是一种很好的做法。由于您已经在页面中包含了 jQuery,因此您最好坚持使用它。尝试这个:

$('button').on('click', function() {
  let value = this.value;
  $($(this).data('target')).val(value).trigger('input');
});

$('.field').on('input', function() {
  let tot = 0;
  $("form#lines-form-1 :input").each((i, el) => tot += parseInt(el.value || 0, 10));
  $('#tot-qty').text(tot);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>
  <text>Field A</text>
  <button type="button" id="80" data-target="#i1" value="80">80</button>
  <button type="button" id="50" data-target="#i1" value="50">50</button>
</div>

<div>
  <text>Field B</text>
  <button type="button" id="80" data-target="#i2" value="80">80</button>
  <button type="button" id="50" data-target="#i2" value="50">50</button>
</div>


<form id="lines-form-1">
  <label>Field A</label>
  <input type="text" class="field" id="i1" name="i1"><br>

  <label>Field B</label>
  <input type="text" class="field" id="i2" name="i2"><br>
</form>

<div id="tot-qty">0</div>


推荐阅读