javascript - 我的 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>
解决方案
问题是因为手动更改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>
推荐阅读
- awk - 如何用 SED (bash) 替换 2 个标签之间的内容?
- python - 当数据库在容器中运行时,如何使用 alembic 自动生成和应用迁移?
- python - 502 错误网关 nginx
- textures - 仅烘焙纹理法线(Blender 2.92)
- c++ - C++ Malloc 不调用 mmap 或 brk?
- docker - 在 docker swarm 中使用 https 运行 gitlab 和 jenkins
- python - 将 3D numpy 矩阵重塑为 2D numpy 矩阵,保持行位置
- c++ - 非静态成员引用必须相对于特定对象 c++
- python - 如何替换数组的多个连续部分?
- angular - 更改后文本框未立即更新